<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="generator" content="Asciidoctor 2.0.10">
<meta name="author" content="尚硅谷大数据讲师左元">
<title>尚硅谷Flink教程</title>
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Open+Sans:300,300italic,400,400italic,600,600italic%7CNoto+Serif:400,400italic,700,700italic%7CDroid+Sans+Mono:400,700">
<style>
/* Asciidoctor default stylesheet | MIT License | https://asciidoctor.org */
/* Uncomment @import statement to use as custom stylesheet */
/*@import "https://fonts.googleapis.com/css?family=Open+Sans:300,300italic,400,400italic,600,600italic%7CNoto+Serif:400,400italic,700,700italic%7CDroid+Sans+Mono:400,700";*/
article,aside,details,figcaption,figure,footer,header,hgroup,main,nav,section{display:block}
audio,video{display:inline-block}
audio:not([controls]){display:none;height:0}
html{font-family:sans-serif;-ms-text-size-adjust:100%;-webkit-text-size-adjust:100%}
a{background:none}
a:focus{outline:thin dotted}
a:active,a:hover{outline:0}
h1{font-size:2em;margin:.67em 0}
abbr[title]{border-bottom:1px dotted}
b,strong{font-weight:bold}
dfn{font-style:italic}
hr{-moz-box-sizing:content-box;box-sizing:content-box;height:0}
mark{background:#ff0;color:#000}
code,kbd,pre,samp{font-family:monospace;font-size:1em}
pre{white-space:pre-wrap}
q{quotes:"\201C" "\201D" "\2018" "\2019"}
small{font-size:80%}
sub,sup{font-size:75%;line-height:0;position:relative;vertical-align:baseline}
sup{top:-.5em}
sub{bottom:-.25em}
img{border:0}
svg:not(:root){overflow:hidden}
figure{margin:0}
fieldset{border:1px solid silver;margin:0 2px;padding:.35em .625em .75em}
legend{border:0;padding:0}
button,input,select,textarea{font-family:inherit;font-size:100%;margin:0}
button,input{line-height:normal}
button,select{text-transform:none}
button,html input[type="button"],input[type="reset"],input[type="submit"]{-webkit-appearance:button;cursor:pointer}
button[disabled],html input[disabled]{cursor:default}
input[type="checkbox"],input[type="radio"]{box-sizing:border-box;padding:0}
button::-moz-focus-inner,input::-moz-focus-inner{border:0;padding:0}
textarea{overflow:auto;vertical-align:top}
table{border-collapse:collapse;border-spacing:0}
*,*::before,*::after{-moz-box-sizing:border-box;-webkit-box-sizing:border-box;box-sizing:border-box}
html,body{font-size:100%}
body{background:#fff;color:rgba(0,0,0,.8);padding:0;margin:0;font-family:"Noto Serif","DejaVu Serif",serif;font-weight:400;font-style:normal;line-height:1;position:relative;cursor:auto;tab-size:4;-moz-osx-font-smoothing:grayscale;-webkit-font-smoothing:antialiased}
a:hover{cursor:pointer}
img,object,embed{max-width:100%;height:auto}
object,embed{height:100%}
img{-ms-interpolation-mode:bicubic}
.left{float:left!important}
.right{float:right!important}
.text-left{text-align:left!important}
.text-right{text-align:right!important}
.text-center{text-align:center!important}
.text-justify{text-align:justify!important}
.hide{display:none}
img,object,svg{display:inline-block;vertical-align:middle}
textarea{height:auto;min-height:50px}
select{width:100%}
.center{margin-left:auto;margin-right:auto}
.stretch{width:100%}
.subheader,.admonitionblock td.content>.title,.audioblock>.title,.exampleblock>.title,.imageblock>.title,.listingblock>.title,.literalblock>.title,.stemblock>.title,.openblock>.title,.paragraph>.title,.quoteblock>.title,table.tableblock>.title,.verseblock>.title,.videoblock>.title,.dlist>.title,.olist>.title,.ulist>.title,.qlist>.title,.hdlist>.title{line-height:1.45;color:#7a2518;font-weight:400;margin-top:0;margin-bottom:.25em}
div,dl,dt,dd,ul,ol,li,h1,h2,h3,#toctitle,.sidebarblock>.content>.title,h4,h5,h6,pre,form,p,blockquote,th,td{margin:0;padding:0;direction:ltr}
a{color:#2156a5;text-decoration:underline;line-height:inherit}
a:hover,a:focus{color:#1d4b8f}
a img{border:0}
p{font-family:inherit;font-weight:400;font-size:1em;line-height:1.6;margin-bottom:1.25em;text-rendering:optimizeLegibility}
p aside{font-size:.875em;line-height:1.35;font-style:italic}
h1,h2,h3,#toctitle,.sidebarblock>.content>.title,h4,h5,h6{font-family:"Open Sans","DejaVu Sans",sans-serif;font-weight:300;font-style:normal;color:#ba3925;text-rendering:optimizeLegibility;margin-top:1em;margin-bottom:.5em;line-height:1.0125em}
h1 small,h2 small,h3 small,#toctitle small,.sidebarblock>.content>.title small,h4 small,h5 small,h6 small{font-size:60%;color:#e99b8f;line-height:0}
h1{font-size:2.125em}
h2{font-size:1.6875em}
h3,#toctitle,.sidebarblock>.content>.title{font-size:1.375em}
h4,h5{font-size:1.125em}
h6{font-size:1em}
hr{border:solid #dddddf;border-width:1px 0 0;clear:both;margin:1.25em 0 1.1875em;height:0}
em,i{font-style:italic;line-height:inherit}
strong,b{font-weight:bold;line-height:inherit}
small{font-size:60%;line-height:inherit}
code{font-family:"Droid Sans Mono","DejaVu Sans Mono",monospace;font-weight:400;color:rgba(0,0,0,.9)}
ul,ol,dl{font-size:1em;line-height:1.6;margin-bottom:1.25em;list-style-position:outside;font-family:inherit}
ul,ol{margin-left:1.5em}
ul li ul,ul li ol{margin-left:1.25em;margin-bottom:0;font-size:1em}
ul.square li ul,ul.circle li ul,ul.disc li ul{list-style:inherit}
ul.square{list-style-type:square}
ul.circle{list-style-type:circle}
ul.disc{list-style-type:disc}
ol li ul,ol li ol{margin-left:1.25em;margin-bottom:0}
dl dt{margin-bottom:.3125em;font-weight:bold}
dl dd{margin-bottom:1.25em}
abbr,acronym{text-transform:uppercase;font-size:90%;color:rgba(0,0,0,.8);border-bottom:1px dotted #ddd;cursor:help}
abbr{text-transform:none}
blockquote{margin:0 0 1.25em;padding:.5625em 1.25em 0 1.1875em;border-left:1px solid #ddd}
blockquote cite{display:block;font-size:.9375em;color:rgba(0,0,0,.6)}
blockquote cite::before{content:"\2014 \0020"}
blockquote cite a,blockquote cite a:visited{color:rgba(0,0,0,.6)}
blockquote,blockquote p{line-height:1.6;color:rgba(0,0,0,.85)}
@media screen and (min-width:768px){h1,h2,h3,#toctitle,.sidebarblock>.content>.title,h4,h5,h6{line-height:1.2}
h1{font-size:2.75em}
h2{font-size:2.3125em}
h3,#toctitle,.sidebarblock>.content>.title{font-size:1.6875em}
h4{font-size:1.4375em}}
table{background:#fff;margin-bottom:1.25em;border:solid 1px #dedede}
table thead,table tfoot{background:#f7f8f7}
table thead tr th,table thead tr td,table tfoot tr th,table tfoot tr td{padding:.5em .625em .625em;font-size:inherit;color:rgba(0,0,0,.8);text-align:left}
table tr th,table tr td{padding:.5625em .625em;font-size:inherit;color:rgba(0,0,0,.8)}
table tr.even,table tr.alt{background:#f8f8f7}
table thead tr th,table tfoot tr th,table tbody tr td,table tr td,table tfoot tr td{display:table-cell;line-height:1.6}
h1,h2,h3,#toctitle,.sidebarblock>.content>.title,h4,h5,h6{line-height:1.2;word-spacing:-.05em}
h1 strong,h2 strong,h3 strong,#toctitle strong,.sidebarblock>.content>.title strong,h4 strong,h5 strong,h6 strong{font-weight:400}
.clearfix::before,.clearfix::after,.float-group::before,.float-group::after{content:" ";display:table}
.clearfix::after,.float-group::after{clear:both}
:not(pre):not([class^=L])>code{font-size:.9375em;font-style:normal!important;letter-spacing:0;padding:.1em .5ex;word-spacing:-.15em;background:#f7f7f8;-webkit-border-radius:4px;border-radius:4px;line-height:1.45;text-rendering:optimizeSpeed;word-wrap:break-word}
:not(pre)>code.nobreak{word-wrap:normal}
:not(pre)>code.nowrap{white-space:nowrap}
pre{color:rgba(0,0,0,.9);font-family:"Droid Sans Mono","DejaVu Sans Mono",monospace;line-height:1.45;text-rendering:optimizeSpeed}
pre code,pre pre{color:inherit;font-size:inherit;line-height:inherit}
pre>code{display:block}
pre.nowrap,pre.nowrap pre{white-space:pre;word-wrap:normal}
em em{font-style:normal}
strong strong{font-weight:400}
.keyseq{color:rgba(51,51,51,.8)}
kbd{font-family:"Droid Sans Mono","DejaVu Sans Mono",monospace;display:inline-block;color:rgba(0,0,0,.8);font-size:.65em;line-height:1.45;background:#f7f7f7;border:1px solid #ccc;-webkit-border-radius:3px;border-radius:3px;-webkit-box-shadow:0 1px 0 rgba(0,0,0,.2),0 0 0 .1em white inset;box-shadow:0 1px 0 rgba(0,0,0,.2),0 0 0 .1em #fff inset;margin:0 .15em;padding:.2em .5em;vertical-align:middle;position:relative;top:-.1em;white-space:nowrap}
.keyseq kbd:first-child{margin-left:0}
.keyseq kbd:last-child{margin-right:0}
.menuseq,.menuref{color:#000}
.menuseq b:not(.caret),.menuref{font-weight:inherit}
.menuseq{word-spacing:-.02em}
.menuseq b.caret{font-size:1.25em;line-height:.8}
.menuseq i.caret{font-weight:bold;text-align:center;width:.45em}
b.button::before,b.button::after{position:relative;top:-1px;font-weight:400}
b.button::before{content:"[";padding:0 3px 0 2px}
b.button::after{content:"]";padding:0 2px 0 3px}
p a>code:hover{color:rgba(0,0,0,.9)}
#header,#content,#footnotes,#footer{width:100%;margin-left:auto;margin-right:auto;margin-top:0;margin-bottom:0;max-width:62.5em;*zoom:1;position:relative;padding-left:.9375em;padding-right:.9375em}
#header::before,#header::after,#content::before,#content::after,#footnotes::before,#footnotes::after,#footer::before,#footer::after{content:" ";display:table}
#header::after,#content::after,#footnotes::after,#footer::after{clear:both}
#content{margin-top:1.25em}
#content::before{content:none}
#header>h1:first-child{color:rgba(0,0,0,.85);margin-top:2.25rem;margin-bottom:0}
#header>h1:first-child+#toc{margin-top:8px;border-top:1px solid #dddddf}
#header>h1:only-child,body.toc2 #header>h1:nth-last-child(2){border-bottom:1px solid #dddddf;padding-bottom:8px}
#header .details{border-bottom:1px solid #dddddf;line-height:1.45;padding-top:.25em;padding-bottom:.25em;padding-left:.25em;color:rgba(0,0,0,.6);display:-ms-flexbox;display:-webkit-flex;display:flex;-ms-flex-flow:row wrap;-webkit-flex-flow:row wrap;flex-flow:row wrap}
#header .details span:first-child{margin-left:-.125em}
#header .details span.email a{color:rgba(0,0,0,.85)}
#header .details br{display:none}
#header .details br+span::before{content:"\00a0\2013\00a0"}
#header .details br+span.author::before{content:"\00a0\22c5\00a0";color:rgba(0,0,0,.85)}
#header .details br+span#revremark::before{content:"\00a0|\00a0"}
#header #revnumber{text-transform:capitalize}
#header #revnumber::after{content:"\00a0"}
#content>h1:first-child:not([class]){color:rgba(0,0,0,.85);border-bottom:1px solid #dddddf;padding-bottom:8px;margin-top:0;padding-top:1rem;margin-bottom:1.25rem}
#toc{border-bottom:1px solid #e7e7e9;padding-bottom:.5em}
#toc>ul{margin-left:.125em}
#toc ul.sectlevel0>li>a{font-style:italic}
#toc ul.sectlevel0 ul.sectlevel1{margin:.5em 0}
#toc ul{font-family:"Open Sans","DejaVu Sans",sans-serif;list-style-type:none}
#toc li{line-height:1.3334;margin-top:.3334em}
#toc a{text-decoration:none}
#toc a:active{text-decoration:underline}
#toctitle{color:#7a2518;font-size:1.2em}
@media screen and (min-width:768px){#toctitle{font-size:1.375em}
body.toc2{padding-left:15em;padding-right:0}
#toc.toc2{margin-top:0!important;background:#f8f8f7;position:fixed;width:15em;left:0;top:0;border-right:1px solid #e7e7e9;border-top-width:0!important;border-bottom-width:0!important;z-index:1000;padding:1.25em 1em;height:100%;overflow:auto}
#toc.toc2 #toctitle{margin-top:0;margin-bottom:.8rem;font-size:1.2em}
#toc.toc2>ul{font-size:.9em;margin-bottom:0}
#toc.toc2 ul ul{margin-left:0;padding-left:1em}
#toc.toc2 ul.sectlevel0 ul.sectlevel1{padding-left:0;margin-top:.5em;margin-bottom:.5em}
body.toc2.toc-right{padding-left:0;padding-right:15em}
body.toc2.toc-right #toc.toc2{border-right-width:0;border-left:1px solid #e7e7e9;left:auto;right:0}}
@media screen and (min-width:1280px){body.toc2{padding-left:20em;padding-right:0}
#toc.toc2{width:20em}
#toc.toc2 #toctitle{font-size:1.375em}
#toc.toc2>ul{font-size:.95em}
#toc.toc2 ul ul{padding-left:1.25em}
body.toc2.toc-right{padding-left:0;padding-right:20em}}
#content #toc{border-style:solid;border-width:1px;border-color:#e0e0dc;margin-bottom:1.25em;padding:1.25em;background:#f8f8f7;-webkit-border-radius:4px;border-radius:4px}
#content #toc>:first-child{margin-top:0}
#content #toc>:last-child{margin-bottom:0}
#footer{max-width:100%;background:rgba(0,0,0,.8);padding:1.25em}
#footer-text{color:rgba(255,255,255,.8);line-height:1.44}
#content{margin-bottom:.625em}
.sect1{padding-bottom:.625em}
@media screen and (min-width:768px){#content{margin-bottom:1.25em}
.sect1{padding-bottom:1.25em}}
.sect1:last-child{padding-bottom:0}
.sect1+.sect1{border-top:1px solid #e7e7e9}
#content h1>a.anchor,h2>a.anchor,h3>a.anchor,#toctitle>a.anchor,.sidebarblock>.content>.title>a.anchor,h4>a.anchor,h5>a.anchor,h6>a.anchor{position:absolute;z-index:1001;width:1.5ex;margin-left:-1.5ex;display:block;text-decoration:none!important;visibility:hidden;text-align:center;font-weight:400}
#content h1>a.anchor::before,h2>a.anchor::before,h3>a.anchor::before,#toctitle>a.anchor::before,.sidebarblock>.content>.title>a.anchor::before,h4>a.anchor::before,h5>a.anchor::before,h6>a.anchor::before{content:"\00A7";font-size:.85em;display:block;padding-top:.1em}
#content h1:hover>a.anchor,#content h1>a.anchor:hover,h2:hover>a.anchor,h2>a.anchor:hover,h3:hover>a.anchor,#toctitle:hover>a.anchor,.sidebarblock>.content>.title:hover>a.anchor,h3>a.anchor:hover,#toctitle>a.anchor:hover,.sidebarblock>.content>.title>a.anchor:hover,h4:hover>a.anchor,h4>a.anchor:hover,h5:hover>a.anchor,h5>a.anchor:hover,h6:hover>a.anchor,h6>a.anchor:hover{visibility:visible}
#content h1>a.link,h2>a.link,h3>a.link,#toctitle>a.link,.sidebarblock>.content>.title>a.link,h4>a.link,h5>a.link,h6>a.link{color:#ba3925;text-decoration:none}
#content h1>a.link:hover,h2>a.link:hover,h3>a.link:hover,#toctitle>a.link:hover,.sidebarblock>.content>.title>a.link:hover,h4>a.link:hover,h5>a.link:hover,h6>a.link:hover{color:#a53221}
details,.audioblock,.imageblock,.literalblock,.listingblock,.stemblock,.videoblock{margin-bottom:1.25em}
details>summary:first-of-type{cursor:pointer;display:list-item;outline:none;margin-bottom:.75em}
.admonitionblock td.content>.title,.audioblock>.title,.exampleblock>.title,.imageblock>.title,.listingblock>.title,.literalblock>.title,.stemblock>.title,.openblock>.title,.paragraph>.title,.quoteblock>.title,table.tableblock>.title,.verseblock>.title,.videoblock>.title,.dlist>.title,.olist>.title,.ulist>.title,.qlist>.title,.hdlist>.title{text-rendering:optimizeLegibility;text-align:left;font-family:"Noto Serif","DejaVu Serif",serif;font-size:1rem;font-style:italic}
table.tableblock.fit-content>caption.title{white-space:nowrap;width:0}
.paragraph.lead>p,#preamble>.sectionbody>[class="paragraph"]:first-of-type p{font-size:1.21875em;line-height:1.6;color:rgba(0,0,0,.85)}
table.tableblock #preamble>.sectionbody>[class="paragraph"]:first-of-type p{font-size:inherit}
.admonitionblock>table{border-collapse:separate;border:0;background:none;width:100%}
.admonitionblock>table td.icon{text-align:center;width:80px}
.admonitionblock>table td.icon img{max-width:none}
.admonitionblock>table td.icon .title{font-weight:bold;font-family:"Open Sans","DejaVu Sans",sans-serif;text-transform:uppercase}
.admonitionblock>table td.content{padding-left:1.125em;padding-right:1.25em;border-left:1px solid #dddddf;color:rgba(0,0,0,.6)}
.admonitionblock>table td.content>:last-child>:last-child{margin-bottom:0}
.exampleblock>.content{border-style:solid;border-width:1px;border-color:#e6e6e6;margin-bottom:1.25em;padding:1.25em;background:#fff;-webkit-border-radius:4px;border-radius:4px}
.exampleblock>.content>:first-child{margin-top:0}
.exampleblock>.content>:last-child{margin-bottom:0}
.sidebarblock{border-style:solid;border-width:1px;border-color:#dbdbd6;margin-bottom:1.25em;padding:1.25em;background:#f3f3f2;-webkit-border-radius:4px;border-radius:4px}
.sidebarblock>:first-child{margin-top:0}
.sidebarblock>:last-child{margin-bottom:0}
.sidebarblock>.content>.title{color:#7a2518;margin-top:0;text-align:center}
.exampleblock>.content>:last-child>:last-child,.exampleblock>.content .olist>ol>li:last-child>:last-child,.exampleblock>.content .ulist>ul>li:last-child>:last-child,.exampleblock>.content .qlist>ol>li:last-child>:last-child,.sidebarblock>.content>:last-child>:last-child,.sidebarblock>.content .olist>ol>li:last-child>:last-child,.sidebarblock>.content .ulist>ul>li:last-child>:last-child,.sidebarblock>.content .qlist>ol>li:last-child>:last-child{margin-bottom:0}
.literalblock pre,.listingblock>.content>pre{-webkit-border-radius:4px;border-radius:4px;word-wrap:break-word;overflow-x:auto;padding:1em;font-size:.8125em}
@media screen and (min-width:768px){.literalblock pre,.listingblock>.content>pre{font-size:.90625em}}
@media screen and (min-width:1280px){.literalblock pre,.listingblock>.content>pre{font-size:1em}}
.literalblock pre,.listingblock>.content>pre:not(.highlight),.listingblock>.content>pre[class="highlight"],.listingblock>.content>pre[class^="highlight "]{background:#f7f7f8}
.literalblock.output pre{color:#f7f7f8;background:rgba(0,0,0,.9)}
.listingblock>.content{position:relative}
.listingblock code[data-lang]::before{display:none;content:attr(data-lang);position:absolute;font-size:.75em;top:.425rem;right:.5rem;line-height:1;text-transform:uppercase;color:inherit;opacity:.5}
.listingblock:hover code[data-lang]::before{display:block}
.listingblock.terminal pre .command::before{content:attr(data-prompt);padding-right:.5em;color:inherit;opacity:.5}
.listingblock.terminal pre .command:not([data-prompt])::before{content:"$"}
.listingblock pre.highlightjs{padding:0}
.listingblock pre.highlightjs>code{padding:1em;-webkit-border-radius:4px;border-radius:4px}
.listingblock pre.prettyprint{border-width:0}
.prettyprint{background:#f7f7f8}
pre.prettyprint .linenums{line-height:1.45;margin-left:2em}
pre.prettyprint li{background:none;list-style-type:inherit;padding-left:0}
pre.prettyprint li code[data-lang]::before{opacity:1}
pre.prettyprint li:not(:first-child) code[data-lang]::before{display:none}
table.linenotable{border-collapse:separate;border:0;margin-bottom:0;background:none}
table.linenotable td[class]{color:inherit;vertical-align:top;padding:0;line-height:inherit;white-space:normal}
table.linenotable td.code{padding-left:.75em}
table.linenotable td.linenos{border-right:1px solid currentColor;opacity:.35;padding-right:.5em}
pre.pygments .lineno{border-right:1px solid currentColor;opacity:.35;display:inline-block;margin-right:.75em}
pre.pygments .lineno::before{content:"";margin-right:-.125em}
.quoteblock{margin:0 1em 1.25em 1.5em;display:table}
.quoteblock:not(.excerpt)>.title{margin-left:-1.5em;margin-bottom:.75em}
.quoteblock blockquote,.quoteblock p{color:rgba(0,0,0,.85);font-size:1.15rem;line-height:1.75;word-spacing:.1em;letter-spacing:0;font-style:italic;text-align:justify}
.quoteblock blockquote{margin:0;padding:0;border:0}
.quoteblock blockquote::before{content:"\201c";float:left;font-size:2.75em;font-weight:bold;line-height:.6em;margin-left:-.6em;color:#7a2518;text-shadow:0 1px 2px rgba(0,0,0,.1)}
.quoteblock blockquote>.paragraph:last-child p{margin-bottom:0}
.quoteblock .attribution{margin-top:.75em;margin-right:.5ex;text-align:right}
.verseblock{margin:0 1em 1.25em}
.verseblock pre{font-family:"Open Sans","DejaVu Sans",sans;font-size:1.15rem;color:rgba(0,0,0,.85);font-weight:300;text-rendering:optimizeLegibility}
.verseblock pre strong{font-weight:400}
.verseblock .attribution{margin-top:1.25rem;margin-left:.5ex}
.quoteblock .attribution,.verseblock .attribution{font-size:.9375em;line-height:1.45;font-style:italic}
.quoteblock .attribution br,.verseblock .attribution br{display:none}
.quoteblock .attribution cite,.verseblock .attribution cite{display:block;letter-spacing:-.025em;color:rgba(0,0,0,.6)}
.quoteblock.abstract blockquote::before,.quoteblock.excerpt blockquote::before,.quoteblock .quoteblock blockquote::before{display:none}
.quoteblock.abstract blockquote,.quoteblock.abstract p,.quoteblock.excerpt blockquote,.quoteblock.excerpt p,.quoteblock .quoteblock blockquote,.quoteblock .quoteblock p{line-height:1.6;word-spacing:0}
.quoteblock.abstract{margin:0 1em 1.25em;display:block}
.quoteblock.abstract>.title{margin:0 0 .375em;font-size:1.15em;text-align:center}
.quoteblock.excerpt>blockquote,.quoteblock .quoteblock{padding:0 0 .25em 1em;border-left:.25em solid #dddddf}
.quoteblock.excerpt,.quoteblock .quoteblock{margin-left:0}
.quoteblock.excerpt blockquote,.quoteblock.excerpt p,.quoteblock .quoteblock blockquote,.quoteblock .quoteblock p{color:inherit;font-size:1.0625rem}
.quoteblock.excerpt .attribution,.quoteblock .quoteblock .attribution{color:inherit;text-align:left;margin-right:0}
table.tableblock{max-width:100%;border-collapse:separate}
p.tableblock:last-child{margin-bottom:0}
td.tableblock>.content>:last-child{margin-bottom:-1.25em}
td.tableblock>.content>:last-child.sidebarblock{margin-bottom:0}
table.tableblock,th.tableblock,td.tableblock{border:0 solid #dedede}
table.grid-all>thead>tr>.tableblock,table.grid-all>tbody>tr>.tableblock{border-width:0 1px 1px 0}
table.grid-all>tfoot>tr>.tableblock{border-width:1px 1px 0 0}
table.grid-cols>*>tr>.tableblock{border-width:0 1px 0 0}
table.grid-rows>thead>tr>.tableblock,table.grid-rows>tbody>tr>.tableblock{border-width:0 0 1px}
table.grid-rows>tfoot>tr>.tableblock{border-width:1px 0 0}
table.grid-all>*>tr>.tableblock:last-child,table.grid-cols>*>tr>.tableblock:last-child{border-right-width:0}
table.grid-all>tbody>tr:last-child>.tableblock,table.grid-all>thead:last-child>tr>.tableblock,table.grid-rows>tbody>tr:last-child>.tableblock,table.grid-rows>thead:last-child>tr>.tableblock{border-bottom-width:0}
table.frame-all{border-width:1px}
table.frame-sides{border-width:0 1px}
table.frame-topbot,table.frame-ends{border-width:1px 0}
table.stripes-all tr,table.stripes-odd tr:nth-of-type(odd),table.stripes-even tr:nth-of-type(even),table.stripes-hover tr:hover{background:#f8f8f7}
th.halign-left,td.halign-left{text-align:left}
th.halign-right,td.halign-right{text-align:right}
th.halign-center,td.halign-center{text-align:center}
th.valign-top,td.valign-top{vertical-align:top}
th.valign-bottom,td.valign-bottom{vertical-align:bottom}
th.valign-middle,td.valign-middle{vertical-align:middle}
table thead th,table tfoot th{font-weight:bold}
tbody tr th{display:table-cell;line-height:1.6;background:#f7f8f7}
tbody tr th,tbody tr th p,tfoot tr th,tfoot tr th p{color:rgba(0,0,0,.8);font-weight:bold}
p.tableblock>code:only-child{background:none;padding:0}
p.tableblock{font-size:1em}
ol{margin-left:1.75em}
ul li ol{margin-left:1.5em}
dl dd{margin-left:1.125em}
dl dd:last-child,dl dd:last-child>:last-child{margin-bottom:0}
ol>li p,ul>li p,ul dd,ol dd,.olist .olist,.ulist .ulist,.ulist .olist,.olist .ulist{margin-bottom:.625em}
ul.checklist,ul.none,ol.none,ul.no-bullet,ol.no-bullet,ol.unnumbered,ul.unstyled,ol.unstyled{list-style-type:none}
ul.no-bullet,ol.no-bullet,ol.unnumbered{margin-left:.625em}
ul.unstyled,ol.unstyled{margin-left:0}
ul.checklist{margin-left:.625em}
ul.checklist li>p:first-child>.fa-square-o:first-child,ul.checklist li>p:first-child>.fa-check-square-o:first-child{width:1.25em;font-size:.8em;position:relative;bottom:.125em}
ul.checklist li>p:first-child>input[type="checkbox"]:first-child{margin-right:.25em}
ul.inline{display:-ms-flexbox;display:-webkit-box;display:flex;-ms-flex-flow:row wrap;-webkit-flex-flow:row wrap;flex-flow:row wrap;list-style:none;margin:0 0 .625em -1.25em}
ul.inline>li{margin-left:1.25em}
.unstyled dl dt{font-weight:400;font-style:normal}
ol.arabic{list-style-type:decimal}
ol.decimal{list-style-type:decimal-leading-zero}
ol.loweralpha{list-style-type:lower-alpha}
ol.upperalpha{list-style-type:upper-alpha}
ol.lowerroman{list-style-type:lower-roman}
ol.upperroman{list-style-type:upper-roman}
ol.lowergreek{list-style-type:lower-greek}
.hdlist>table,.colist>table{border:0;background:none}
.hdlist>table>tbody>tr,.colist>table>tbody>tr{background:none}
td.hdlist1,td.hdlist2{vertical-align:top;padding:0 .625em}
td.hdlist1{font-weight:bold;padding-bottom:1.25em}
.literalblock+.colist,.listingblock+.colist{margin-top:-.5em}
.colist td:not([class]):first-child{padding:.4em .75em 0;line-height:1;vertical-align:top}
.colist td:not([class]):first-child img{max-width:none}
.colist td:not([class]):last-child{padding:.25em 0}
.thumb,.th{line-height:0;display:inline-block;border:solid 4px #fff;-webkit-box-shadow:0 0 0 1px #ddd;box-shadow:0 0 0 1px #ddd}
.imageblock.left{margin:.25em .625em 1.25em 0}
.imageblock.right{margin:.25em 0 1.25em .625em}
.imageblock>.title{margin-bottom:0}
.imageblock.thumb,.imageblock.th{border-width:6px}
.imageblock.thumb>.title,.imageblock.th>.title{padding:0 .125em}
.image.left,.image.right{margin-top:.25em;margin-bottom:.25em;display:inline-block;line-height:0}
.image.left{margin-right:.625em}
.image.right{margin-left:.625em}
a.image{text-decoration:none;display:inline-block}
a.image object{pointer-events:none}
sup.footnote,sup.footnoteref{font-size:.875em;position:static;vertical-align:super}
sup.footnote a,sup.footnoteref a{text-decoration:none}
sup.footnote a:active,sup.footnoteref a:active{text-decoration:underline}
#footnotes{padding-top:.75em;padding-bottom:.75em;margin-bottom:.625em}
#footnotes hr{width:20%;min-width:6.25em;margin:-.25em 0 .75em;border-width:1px 0 0}
#footnotes .footnote{padding:0 .375em 0 .225em;line-height:1.3334;font-size:.875em;margin-left:1.2em;margin-bottom:.2em}
#footnotes .footnote a:first-of-type{font-weight:bold;text-decoration:none;margin-left:-1.05em}
#footnotes .footnote:last-of-type{margin-bottom:0}
#content #footnotes{margin-top:-.625em;margin-bottom:0;padding:.75em 0}
.gist .file-data>table{border:0;background:#fff;width:100%;margin-bottom:0}
.gist .file-data>table td.line-data{width:99%}
div.unbreakable{page-break-inside:avoid}
.big{font-size:larger}
.small{font-size:smaller}
.underline{text-decoration:underline}
.overline{text-decoration:overline}
.line-through{text-decoration:line-through}
.aqua{color:#00bfbf}
.aqua-background{background:#00fafa}
.black{color:#000}
.black-background{background:#000}
.blue{color:#0000bf}
.blue-background{background:#0000fa}
.fuchsia{color:#bf00bf}
.fuchsia-background{background:#fa00fa}
.gray{color:#606060}
.gray-background{background:#7d7d7d}
.green{color:#006000}
.green-background{background:#007d00}
.lime{color:#00bf00}
.lime-background{background:#00fa00}
.maroon{color:#600000}
.maroon-background{background:#7d0000}
.navy{color:#000060}
.navy-background{background:#00007d}
.olive{color:#606000}
.olive-background{background:#7d7d00}
.purple{color:#600060}
.purple-background{background:#7d007d}
.red{color:#bf0000}
.red-background{background:#fa0000}
.silver{color:#909090}
.silver-background{background:#bcbcbc}
.teal{color:#006060}
.teal-background{background:#007d7d}
.white{color:#bfbfbf}
.white-background{background:#fafafa}
.yellow{color:#bfbf00}
.yellow-background{background:#fafa00}
span.icon>.fa{cursor:default}
a span.icon>.fa{cursor:inherit}
.admonitionblock td.icon [class^="fa icon-"]{font-size:2.5em;text-shadow:1px 1px 2px rgba(0,0,0,.5);cursor:default}
.admonitionblock td.icon .icon-note::before{content:"\f05a";color:#19407c}
.admonitionblock td.icon .icon-tip::before{content:"\f0eb";text-shadow:1px 1px 2px rgba(155,155,0,.8);color:#111}
.admonitionblock td.icon .icon-warning::before{content:"\f071";color:#bf6900}
.admonitionblock td.icon .icon-caution::before{content:"\f06d";color:#bf3400}
.admonitionblock td.icon .icon-important::before{content:"\f06a";color:#bf0000}
.conum[data-value]{display:inline-block;color:#fff!important;background:rgba(0,0,0,.8);-webkit-border-radius:100px;border-radius:100px;text-align:center;font-size:.75em;width:1.67em;height:1.67em;line-height:1.67em;font-family:"Open Sans","DejaVu Sans",sans-serif;font-style:normal;font-weight:bold}
.conum[data-value] *{color:#fff!important}
.conum[data-value]+b{display:none}
.conum[data-value]::after{content:attr(data-value)}
pre .conum[data-value]{position:relative;top:-.125em}
b.conum *{color:inherit!important}
.conum:not([data-value]):empty{display:none}
dt,th.tableblock,td.content,div.footnote{text-rendering:optimizeLegibility}
h1,h2,p,td.content,span.alt{letter-spacing:-.01em}
p strong,td.content strong,div.footnote strong{letter-spacing:-.005em}
p,blockquote,dt,td.content,span.alt{font-size:1.0625rem}
p{margin-bottom:1.25rem}
.sidebarblock p,.sidebarblock dt,.sidebarblock td.content,p.tableblock{font-size:1em}
.exampleblock>.content{background:#fffef7;border-color:#e0e0dc;-webkit-box-shadow:0 1px 4px #e0e0dc;box-shadow:0 1px 4px #e0e0dc}
.print-only{display:none!important}
@page{margin:1.25cm .75cm}
@media print{*{-webkit-box-shadow:none!important;box-shadow:none!important;text-shadow:none!important}
html{font-size:80%}
a{color:inherit!important;text-decoration:underline!important}
a.bare,a[href^="#"],a[href^="mailto:"]{text-decoration:none!important}
a[href^="http:"]:not(.bare)::after,a[href^="https:"]:not(.bare)::after{content:"(" attr(href) ")";display:inline-block;font-size:.875em;padding-left:.25em}
abbr[title]::after{content:" (" attr(title) ")"}
pre,blockquote,tr,img,object,svg{page-break-inside:avoid}
thead{display:table-header-group}
svg{max-width:100%}
p,blockquote,dt,td.content{font-size:1em;orphans:3;widows:3}
h2,h3,#toctitle,.sidebarblock>.content>.title{page-break-after:avoid}
#toc,.sidebarblock,.exampleblock>.content{background:none!important}
#toc{border-bottom:1px solid #dddddf!important;padding-bottom:0!important}
body.book #header{text-align:center}
body.book #header>h1:first-child{border:0!important;margin:2.5em 0 1em}
body.book #header .details{border:0!important;display:block;padding:0!important}
body.book #header .details span:first-child{margin-left:0!important}
body.book #header .details br{display:block}
body.book #header .details br+span::before{content:none!important}
body.book #toc{border:0!important;text-align:left!important;padding:0!important;margin:0!important}
body.book #toc,body.book #preamble,body.book h1.sect0,body.book .sect1>h2{page-break-before:always}
.listingblock code[data-lang]::before{display:block}
#footer{padding:0 .9375em}
.hide-on-print{display:none!important}
.print-only{display:block!important}
.hide-for-print{display:none!important}
.show-for-print{display:inherit!important}}
@media print,amzn-kf8{#header>h1:first-child{margin-top:1.25rem}
.sect1{padding:0!important}
.sect1+.sect1{border:0}
#footer{background:none}
#footer-text{color:rgba(0,0,0,.6);font-size:.9em}}
@media amzn-kf8{#header,#content,#footnotes,#footer{padding:0}}
</style>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
</head>
<body class="article toc2 toc-left">
<div id="header">
<h1>尚硅谷Flink教程</h1>
<div class="details">
<span id="author" class="author">尚硅谷大数据讲师左元</span><br>
<span id="email" class="email"><a href="mailto:zuoyuan@atguigu.com">zuoyuan@atguigu.com</a></span><br>
<span id="revnumber">version 1.0,</span>
<span id="revdate">2019-06-01</span>
</div>
<div id="toc" class="toc2">
<div id="toctitle">Table of Contents</div>
<ul class="sectlevel1">
<li><a href="#_有状态的流式处理简介">1. 有状态的流式处理简介</a>
<ul class="sectlevel2">
<li><a href="#_传统数据处理架构">1.1. 传统数据处理架构</a>
<ul class="sectlevel3">
<li><a href="#_事务处理">1.1.1. 事务处理</a></li>
<li><a href="#_分析处理">1.1.2. 分析处理</a></li>
</ul>
</li>
<li><a href="#_有状态的流式处理">1.2. 有状态的流式处理</a>
<ul class="sectlevel3">
<li><a href="#_事件驱动应用程序event_driven_applications">1.2.1. 事件驱动应用程序（Event-Driven Applications）</a></li>
<li><a href="#_数据管道data_pipelines">1.2.2. 数据管道（Data Pipelines）</a></li>
<li><a href="#_流分析">1.2.3. 流分析</a></li>
</ul>
</li>
<li><a href="#_开源流处理的演进">1.3. 开源流处理的演进</a>
<ul class="sectlevel3">
<li><a href="#_流处理的历史">1.3.1. 流处理的历史</a></li>
</ul>
</li>
<li><a href="#_flink_简介">1.4. Flink 简介</a></li>
</ul>
</li>
<li><a href="#_流处理基础">2. 流处理基础</a>
<ul class="sectlevel2">
<li><a href="#_数据流编程简介">2.1. 数据流编程简介</a>
<ul class="sectlevel3">
<li><a href="#_数据流图dataflow_graph">2.1.1. 数据流图(dataflow graph)</a></li>
<li><a href="#_数据并行和任务并行">2.1.2. 数据并行和任务并行</a></li>
<li><a href="#_数据交换策略">2.1.3. 数据交换策略</a></li>
</ul>
</li>
<li><a href="#_并行处理流数据">2.2. 并行处理流数据</a>
<ul class="sectlevel3">
<li><a href="#_延迟和吞吐量">2.2.1. 延迟和吞吐量</a></li>
<li><a href="#_延迟">2.2.2. 延迟</a></li>
<li><a href="#_吞吐量">2.2.3. 吞吐量</a></li>
<li><a href="#_延迟与吞吐量的对比">2.2.4. 延迟与吞吐量的对比</a></li>
</ul>
</li>
<li><a href="#_数据流上的操作">2.3. 数据流上的操作</a>
<ul class="sectlevel3">
<li><a href="#_数据摄入和数据吞吐量">2.3.1. 数据摄入和数据吞吐量</a></li>
<li><a href="#_转换算子">2.3.2. 转换算子</a></li>
<li><a href="#_滚动聚合">2.3.3. 滚动聚合</a></li>
<li><a href="#_窗口操作符">2.3.4. 窗口操作符</a></li>
</ul>
</li>
<li><a href="#_时间语义">2.4. 时间语义</a>
<ul class="sectlevel3">
<li><a href="#_在流处理中一分钟代表什么">2.4.1. 在流处理中一分钟代表什么？</a></li>
<li><a href="#_处理时间">2.4.2. 处理时间</a></li>
<li><a href="#_事件时间">2.4.3. 事件时间</a></li>
<li><a href="#_水位线watermarks">2.4.4. 水位线（Watermarks）</a></li>
<li><a href="#_处理时间_vs_事件时间">2.4.5. 处理时间 vs 事件时间</a></li>
</ul>
</li>
<li><a href="#_状态和持久化模型">2.5. 状态和持久化模型</a>
<ul class="sectlevel3">
<li><a href="#_任务失败">2.5.1. 任务失败</a>
<ul class="sectlevel4">
<li><a href="#_什么是任务失败">什么是任务失败？</a></li>
<li><a href="#_结果的保证">结果的保证</a></li>
</ul>
</li>
</ul>
</li>
</ul>
</li>
<li><a href="#_flink运行架构">3. Flink运行架构</a>
<ul class="sectlevel2">
<li><a href="#_系统架构">3.1. 系统架构</a>
<ul class="sectlevel3">
<li><a href="#_flink运行时组件">3.1.1. Flink运行时组件</a></li>
<li><a href="#_应用部署">3.1.2. 应用部署</a></li>
<li><a href="#_任务执行">3.1.3. 任务执行</a></li>
<li><a href="#_高可用配置">3.1.4. 高可用配置</a></li>
</ul>
</li>
<li><a href="#_flink中的数据传输">3.2. Flink中的数据传输</a>
<ul class="sectlevel3">
<li><a href="#_基于信任度credit的流控制">3.2.1. 基于信任度（credit）的流控制</a></li>
<li><a href="#_任务链task_chaining">3.2.2. 任务链（Task Chaining）</a></li>
</ul>
</li>
<li><a href="#_事件时间event_time处理">3.3. 事件时间（Event-Time）处理</a>
<ul class="sectlevel3">
<li><a href="#_时间戳timestamps">3.3.1. 时间戳（Timestamps）</a></li>
<li><a href="#_水位线watermarks_2">3.3.2. 水位线(Watermarks)</a></li>
<li><a href="#_watermark的传递和事件时间">3.3.3. watermark的传递和事件时间</a></li>
<li><a href="#_时间戳的分配和水位线的产生">3.3.4. 时间戳的分配和水位线的产生</a></li>
</ul>
</li>
<li><a href="#_状态管理">3.4. 状态管理</a>
<ul class="sectlevel3">
<li><a href="#_算子状态">3.4.1. 算子状态</a>
<ul class="sectlevel4">
<li><a href="#_列表状态list_state">列表状态（List state）</a></li>
<li><a href="#_联合列表状态union_list_state">联合列表状态（Union list state）</a></li>
<li><a href="#_广播状态broadcast_state">广播状态（Broadcast state）</a></li>
</ul>
</li>
<li><a href="#_键控状态keyed_state">3.4.2. 键控状态（Keyed State）</a>
<ul class="sectlevel4">
<li><a href="#_值状态value_state">值状态（Value state）</a></li>
<li><a href="#_列表状态list_state_2">列表状态（List state）</a></li>
<li><a href="#_映射状态map_state">映射状态（Map state）</a></li>
</ul>
</li>
<li><a href="#_状态后端state_backends">3.4.3. 状态后端（State Backends）</a></li>
<li><a href="#_调整有状态算子的并行度">3.4.4. 调整有状态算子的并行度</a></li>
</ul>
</li>
<li><a href="#_检查点保存点和状态恢复">3.5. 检查点，保存点和状态恢复</a>
<ul class="sectlevel3">
<li><a href="#_一致的检查点checkpoints">3.5.1. 一致的检查点（Checkpoints）</a></li>
<li><a href="#_从一致检查点中恢复状态">3.5.2. 从一致检查点中恢复状态</a></li>
<li><a href="#_flink的检查点算法">3.5.3. Flink的检查点算法</a></li>
<li><a href="#_检查点的性能影响">3.5.4. 检查点的性能影响</a></li>
<li><a href="#_保存点savepoints">3.5.5. 保存点（Savepoints）</a>
<ul class="sectlevel4">
<li><a href="#_使用保存点">使用保存点</a></li>
<li><a href="#_从保存点启动应用程序">从保存点启动应用程序</a></li>
</ul>
</li>
</ul>
</li>
</ul>
</li>
<li><a href="#_编写第一个flink程序">4. 编写第一个Flink程序</a>
<ul class="sectlevel2">
<li><a href="#_在idea中编写flink程序">4.1. 在IDEA中编写Flink程序</a></li>
<li><a href="#_下载flink运行时环境提交jar包的运行方式">4.2. 下载Flink运行时环境，提交Jar包的运行方式</a></li>
</ul>
</li>
<li><a href="#_flink_datastream_api">5. Flink DataStream API</a>
<ul class="sectlevel2">
<li><a href="#_你好flink">5.1. 你好，Flink！</a></li>
<li><a href="#_搭建执行环境">5.2. 搭建执行环境</a></li>
<li><a href="#_读取输入流">5.3. 读取输入流</a></li>
<li><a href="#_转换算子的使用">5.4. 转换算子的使用</a></li>
<li><a href="#_输出结果">5.5. 输出结果</a></li>
<li><a href="#_执行">5.6. 执行</a></li>
<li><a href="#_产生传感器读数代码编写">5.7. 产生传感器读数代码编写</a>
<ul class="sectlevel3">
<li><a href="#_从批读取数据">5.7.1. 从批读取数据</a></li>
<li><a href="#_从文件读取数据">5.7.2. 从文件读取数据</a></li>
<li><a href="#_以kafka消息队列的数据为数据来源">5.7.3. 以Kafka消息队列的数据为数据来源</a></li>
<li><a href="#_自定义数据源">5.7.4. 自定义数据源</a></li>
</ul>
</li>
<li><a href="#_转换算子_2">5.8. 转换算子</a>
<ul class="sectlevel3">
<li><a href="#_基本转换算子">5.8.1. 基本转换算子</a></li>
<li><a href="#_键控流转换算子">5.8.2. 键控流转换算子</a></li>
<li><a href="#_多流转换算子">5.8.3. 多流转换算子</a></li>
<li><a href="#_分布式转换算子">5.8.4. 分布式转换算子</a></li>
</ul>
</li>
<li><a href="#_设置并行度">5.9. 设置并行度</a></li>
<li><a href="#_类型">5.10. 类型</a>
<ul class="sectlevel3">
<li><a href="#_支持的数据类型">5.10.1. 支持的数据类型</a></li>
<li><a href="#_为数据类型创建类型信息">5.10.2. 为数据类型创建类型信息</a></li>
</ul>
</li>
<li><a href="#_定义key以及引用字段">5.11. 定义Key以及引用字段</a>
<ul class="sectlevel3">
<li><a href="#_使用字段位置进行keyby">5.11.1. 使用字段位置进行keyBy</a></li>
<li><a href="#_使用字段表达式来进行keyby">5.11.2. 使用字段表达式来进行keyBy</a></li>
<li><a href="#_key选择器">5.11.3. Key选择器</a></li>
</ul>
</li>
<li><a href="#_实现udf函数更细粒度的控制流">5.12. 实现UDF函数，更细粒度的控制流</a>
<ul class="sectlevel3">
<li><a href="#_函数类function_classes">5.12.1. 函数类(Function Classes)</a></li>
<li><a href="#_匿名函数lambda_functions">5.12.2. 匿名函数(Lambda Functions)</a></li>
<li><a href="#_富函数rich_functions">5.12.3. 富函数(Rich Functions)</a></li>
</ul>
</li>
<li><a href="#_sink">5.13. Sink</a>
<ul class="sectlevel3">
<li><a href="#_kafka">5.13.1. Kafka</a></li>
<li><a href="#_redis">5.13.2. Redis</a></li>
<li><a href="#_elasticsearch">5.13.3. ElasticSearch</a></li>
<li><a href="#_jdbc自定义sink">5.13.4. JDBC自定义sink</a></li>
</ul>
</li>
</ul>
</li>
<li><a href="#_基于时间和窗口的操作符">6. 基于时间和窗口的操作符</a>
<ul class="sectlevel2">
<li><a href="#_设置时间属性">6.1. 设置时间属性</a>
<ul class="sectlevel3">
<li><a href="#_指定时间戳和产生水位线">6.1.1. 指定时间戳和产生水位线</a></li>
<li><a href="#_周期性的生成水位线">6.1.2. 周期性的生成水位线</a></li>
<li><a href="#_如何产生不规则的水位线">6.1.3. 如何产生不规则的水位线</a></li>
</ul>
</li>
<li><a href="#_process_functionlow_level_api">6.2. Process Function(Low-Level API)</a>
<ul class="sectlevel3">
<li><a href="#_timerservice_and_timers">6.2.1. TimerService and Timers</a></li>
<li><a href="#_将事件发送到侧输出emitting_to_side_outputs">6.2.2. 将事件发送到侧输出(Emitting to Side Outputs)</a></li>
<li><a href="#_coprocessfunction">6.2.3. CoProcessFunction</a></li>
</ul>
</li>
<li><a href="#_窗口操作符window_operators">6.3. 窗口操作符(Window Operators)</a>
<ul class="sectlevel3">
<li><a href="#_定义窗口操作符">6.3.1. 定义窗口操作符</a></li>
<li><a href="#_内置的窗口分配器built_in_window_assigner">6.3.2. 内置的窗口分配器(built-in window assigner)</a></li>
<li><a href="#_调用窗口计算函数">6.3.3. 调用窗口计算函数</a></li>
<li><a href="#_自定义窗口操作符windows_operators">6.3.4. 自定义窗口操作符(windows operators)</a></li>
</ul>
</li>
<li><a href="#_处理迟到的元素handling_late_data">6.4. 处理迟到的元素(Handling Late Data)</a>
<ul class="sectlevel3">
<li><a href="#_抛弃迟到元素">6.4.1. 抛弃迟到元素</a></li>
<li><a href="#_重定向迟到元素">6.4.2. 重定向迟到元素</a></li>
<li><a href="#_使用迟到元素更新窗口计算结果updating_results_by_including_late_events">6.4.3. 使用迟到元素更新窗口计算结果(Updating Results by Including Late Events)</a></li>
</ul>
</li>
</ul>
</li>
<li><a href="#_有状态的计算">7. 有状态的计算</a>
<ul class="sectlevel2">
<li><a href="#_实现有状态的用户自定义函数">7.1. 实现有状态的用户自定义函数</a>
<ul class="sectlevel3">
<li><a href="#_在runtimecontext中定义键控状态keyed_state">7.1.1. 在RuntimeContext中定义键控状态(keyed state)</a></li>
<li><a href="#_使用listcheckpointed接口来实现操作符的列表状态list_state">7.1.2. 使用ListCheckpointed接口来实现操作符的列表状态(List State)</a></li>
<li><a href="#_使用连接的广播状态using_connected_broadcast_state">7.1.3. 使用连接的广播状态(using connected broadcast state)</a></li>
</ul>
</li>
<li><a href="#_配置检查点">7.2. 配置检查点</a>
<ul class="sectlevel3">
<li><a href="#_将hdfs配置为状态后端">7.2.1. 将hdfs配置为状态后端</a></li>
</ul>
</li>
<li><a href="#_保证有状态应用的可维护性">7.3. 保证有状态应用的可维护性</a>
<ul class="sectlevel3">
<li><a href="#_指定唯一的操作符标识符operator_identifiers">7.3.1. 指定唯一的操作符标识符(operator identifiers)</a></li>
<li><a href="#_指定操作符的最大并行度">7.3.2. 指定操作符的最大并行度</a></li>
</ul>
</li>
<li><a href="#_有状态应用的性能和健壮性">7.4. 有状态应用的性能和健壮性</a>
<ul class="sectlevel3">
<li><a href="#_选择一个状态后端">7.4.1. 选择一个状态后端</a></li>
<li><a href="#_防止状态泄露">7.4.2. 防止状态泄露</a></li>
</ul>
</li>
</ul>
</li>
<li><a href="#_从外部系统读取以及写入外部系统">8. 从外部系统读取以及写入外部系统</a>
<ul class="sectlevel2">
<li><a href="#_应用的一致性保证">8.1. 应用的一致性保证</a>
<ul class="sectlevel3">
<li><a href="#_幂等性写入">8.1.1. 幂等性写入</a></li>
<li><a href="#_事务性写入">8.1.2. 事务性写入</a></li>
</ul>
</li>
<li><a href="#_flink提供的连接器">8.2. Flink提供的连接器</a>
<ul class="sectlevel3">
<li><a href="#_apache_kafka_source连接器">8.2.1. Apache Kafka Source连接器</a></li>
<li><a href="#_apache_kafka_sink连接器">8.2.2. Apache Kafka Sink连接器</a></li>
<li><a href="#_kakfa_sink的at_least_once保证">8.2.3. Kakfa Sink的at-least-once保证</a></li>
<li><a href="#_kafka_sink的恰好处理一次语义保证">8.2.4. Kafka Sink的恰好处理一次语义保证</a></li>
<li><a href="#_文件系统source连接器">8.2.5. 文件系统source连接器</a></li>
<li><a href="#_文件系统sink连接器">8.2.6. 文件系统sink连接器</a></li>
</ul>
</li>
<li><a href="#_实现自定义源函数">8.3. 实现自定义源函数</a>
<ul class="sectlevel3">
<li><a href="#_可重置的源函数">8.3.1. 可重置的源函数</a></li>
</ul>
</li>
<li><a href="#_实现自定义sink函数">8.4. 实现自定义sink函数</a>
<ul class="sectlevel3">
<li><a href="#_幂等sink连接器">8.4.1. 幂等sink连接器</a></li>
<li><a href="#_事务性sink连接器">8.4.2. 事务性sink连接器</a></li>
</ul>
</li>
</ul>
</li>
<li><a href="#_flink部署与运维">9. Flink部署与运维</a>
<ul class="sectlevel2">
<li><a href="#_部署方式">9.1. 部署方式</a>
<ul class="sectlevel3">
<li><a href="#_standalone集群">9.1.1. standalone集群</a></li>
<li><a href="#_apache_hadoop_yarn">9.1.2. Apache Hadoop Yarn</a></li>
</ul>
</li>
<li><a href="#_高可用配置ha">9.2. 高可用配置(HA)</a>
<ul class="sectlevel3">
<li><a href="#_standalone集群高可用配置">9.2.1. standalone集群高可用配置</a></li>
<li><a href="#_yarn集群高可用配置">9.2.2. yarn集群高可用配置</a></li>
</ul>
</li>
<li><a href="#_与hadoop集成">9.3. 与Hadoop集成</a></li>
<li><a href="#_保存点操作">9.4. 保存点操作</a></li>
<li><a href="#_取消一个应用">9.5. 取消一个应用</a></li>
<li><a href="#_从保存点启动应用程序_2">9.6. 从保存点启动应用程序</a></li>
<li><a href="#_扩容改变并行度操作">9.7. 扩容，改变并行度操作</a></li>
</ul>
</li>
<li><a href="#_flink_cep简介">10. Flink CEP简介</a></li>
<li><a href="#_flink_table_api_sql">11. Flink Table API &amp; SQL</a>
<ul class="sectlevel2">
<li><a href="#_导入依赖">11.1. 导入依赖</a></li>
<li><a href="#_简单了解table_api">11.2. 简单了解Table API</a>
<ul class="sectlevel3">
<li><a href="#_动态表">11.2.1. 动态表</a></li>
<li><a href="#_字段">11.2.2. 字段</a></li>
</ul>
</li>
<li><a href="#_table_api_的窗口聚合操作">11.3. Table API 的窗口聚合操作</a>
<ul class="sectlevel3">
<li><a href="#_通过一个例子了解tableapi">11.3.1. 通过一个例子了解TableAPI</a></li>
<li><a href="#_关于group_by">11.3.2. 关于group by</a></li>
<li><a href="#_关于时间窗口">11.3.3. 关于时间窗口</a></li>
</ul>
</li>
<li><a href="#_sql如何编写">11.4. SQL如何编写</a></li>
<li><a href="#_使用table_api结合sql实现topn需求">11.5. 使用Table API结合SQL实现TopN需求</a></li>
<li><a href="#_只使用flink_sql实现topn需求">11.6. 只使用Flink SQL实现TopN需求</a></li>
<li><a href="#_用户自定义函数">11.7. 用户自定义函数</a>
<ul class="sectlevel3">
<li><a href="#_scalar_functions">11.7.1. Scalar Functions</a></li>
<li><a href="#_table_functions">11.7.2. Table Functions</a></li>
<li><a href="#_aggregation_functions">11.7.3. Aggregation Functions</a></li>
<li><a href="#_table_aggregation_functions">11.7.4. Table Aggregation Functions</a></li>
</ul>
</li>
</ul>
</li>
<li><a href="#_尚硅谷大数据技术之电商用户行为分析">12. 尚硅谷大数据技术之电商用户行为分析</a>
<ul class="sectlevel2">
<li><a href="#_数据集解析">12.1. 数据集解析</a>
<ul class="sectlevel3">
<li><a href="#_淘宝数据集解析">12.1.1. 淘宝数据集解析</a></li>
<li><a href="#_apache服务器日志数据集解析">12.1.2. Apache服务器日志数据集解析</a></li>
</ul>
</li>
<li><a href="#_实时热门商品统计">12.2. 实时热门商品统计</a></li>
<li><a href="#_实时流量统计">12.3. 实时流量统计</a></li>
<li><a href="#_uv统计的布隆过滤器实现">12.4. Uv统计的布隆过滤器实现</a></li>
<li><a href="#_app分渠道数据统计">12.5. APP分渠道数据统计</a></li>
<li><a href="#_app不分渠道数据统计">12.6. APP不分渠道数据统计</a></li>
<li><a href="#_恶意登陆实现">12.7. 恶意登陆实现</a></li>
<li><a href="#_订单支付实时监控">12.8. 订单支付实时监控</a>
<ul class="sectlevel3">
<li><a href="#_使用flink_cep来实现">12.8.1. 使用Flink CEP来实现</a></li>
<li><a href="#_使用process_function实现订单超时需求">12.8.2. 使用Process Function实现订单超时需求</a></li>
</ul>
</li>
<li><a href="#_实现两条流的join">12.9. 实现两条流的Join</a></li>
</ul>
</li>
<li><a href="#_常见面试题解答">13. 常见面试题解答</a>
<ul class="sectlevel2">
<li><a href="#_面试题一">13.1. 面试题一</a></li>
<li><a href="#_面试题二">13.2. 面试题二</a></li>
<li><a href="#_面试题三">13.3. 面试题三</a></li>
<li><a href="#_面试题四">13.4. 面试题四</a></li>
<li><a href="#_面试题五">13.5. 面试题五</a></li>
<li><a href="#_面试题六">13.6. 面试题六</a></li>
<li><a href="#_面试题七">13.7. 面试题七</a></li>
<li><a href="#_面试题八">13.8. 面试题八</a></li>
<li><a href="#_面试题九">13.9. 面试题九</a></li>
<li><a href="#_面试题十">13.10. 面试题十</a></li>
<li><a href="#_面试题十一">13.11. 面试题十一</a></li>
<li><a href="#_面试题十二">13.12. 面试题十二</a></li>
<li><a href="#_面试题十三">13.13. 面试题十三</a></li>
<li><a href="#_面试题十四">13.14. 面试题十四</a></li>
<li><a href="#_面试题十五">13.15. 面试题十五</a></li>
<li><a href="#_面试题十六">13.16. 面试题十六</a></li>
<li><a href="#_面试题十七">13.17. 面试题十七</a></li>
</ul>
</li>
</ul>
</div>
</div>
<div id="content">
<div class="sect1">
<h2 id="_有状态的流式处理简介">1. 有状态的流式处理简介</h2>
<div class="sectionbody">
<div class="paragraph">
<p>Apache Flink是一个分布式流处理器，具有直观和富有表现力的API，可实现有状态的流处理应用程序。它以容错的方式有效地大规模运行这些应用程序。 Flink于2014年4月加入Apache软件基金会作为孵化项目，并于2015年1月成为顶级项目。从一开始，Flink就拥有一个非常活跃且不断增长的用户和贡献者社区。到目前为止，已有超过五百人为Flink做出贡献，并且它已经发展成为最复杂的开源流处理引擎之一，并得到了广泛采用的证明。 Flink为不同行业和全球的许多公司和企业提供大规模的商业关键应用。</p>
</div>
<div class="paragraph">
<p>流处理技术在大大小小的公司中越来越受欢迎，因为它为许多已建立的用例（如数据分析，ETL和事务应用程序）提供了卓越的解决方案，同时也促进了新颖的应用程序，软件架构和商机。接下来我们将讨论，为什么有状态流处理变得如此受欢迎并评估其潜力。我们首先回顾传统的数据应用程序架构并指出它们的局限性。接下来，我们介绍基于状态流处理的应用程序设计 与传统方法相比，它具有许多有趣的特征最后，我们简要讨论开源流处理器的发展，并在本地Flink实例上运行流应用程序。</p>
</div>
<div class="sect2">
<h3 id="_传统数据处理架构">1.1. 传统数据处理架构</h3>
<div class="paragraph">
<p>数十年来，数据和数据处理在企业中无处不在。多年来，数据的收集和使用一直在增长，公司已经设计并构建了基础架构来管理数据。大多数企业实施的传统架构区分了两种类型的数据处理：事务处理（OLTP）和分析处理（OLAP）。</p>
</div>
<div class="sect3">
<h4 id="_事务处理">1.1.1. 事务处理</h4>
<div class="paragraph">
<p>公司将各种应用程序用于日常业务活动，例如企业资源规划（ERP）系统，客户关系管理（CRM）软件和基于Web的应用程序。这些系统通常设计有单独的层，用于数据处理（应用程序本身）和数据存储（事务数据库系统），如图1-1所示。</p>
</div>
<div class="imageblock">
<div class="content">
<img src="images/spaf_0101.png" alt="spaf 0101">
</div>
</div>
<div class="paragraph">
<p>应用程序通常连接到外部服务或直接面向用户，并持续处理传入的事件，如网站上的订单，电子邮件或点击。处理事件时，应用程序将会读取远程数据库的状态，或者通过运行事务来更新它。通常，一个数据库系统可以服务于多个应用程序，它们有时会访问相同的数据库或表。</p>
</div>
<div class="paragraph">
<p>当应用程序需要扩展时，这样的设计可能会导致问题。由于多个应用程序可能会同时用到相同的数据表示，或者共享相同的基础设施，因此想要更改表的结构或扩展数据库，就需要仔细的规划和大量的工作。克服紧耦合应用程序的最新方法是微服务设计模式。微服务被设计为小型、完备且独立的应用程序。他们遵循UNIX的理念，即“只做一件事并且把它做好”。通过将几个微服务相互连接来构建更复杂的应用程序，这些微服务仅通过标准化接口（例如RESTful HTTP连接）进行通信。由于微服务严格地彼此分离并且仅通过明确定义的接口进行通信，因此每个微服务都可以用不同技术栈来实现，包括编程语言、类库和数据存储。微服务和所有必需的软件和服务通常捆绑在一起并部署在独立的容器中。图1-2描绘了一种微服务架构。</p>
</div>
<div class="imageblock">
<div class="content">
<img src="images/spaf_0102.png" alt="spaf 0102">
</div>
</div>
</div>
<div class="sect3">
<h4 id="_分析处理">1.1.2. 分析处理</h4>
<div class="paragraph">
<p>大量数据存储在公司的各种事务数据库系统中，它们可以为公司业务运营提供宝贵的参考意见。例如，分析订单处理系统的数据，可以获得销量随时间的增长曲线；可以识别延迟发货的原因；还可以预测未来的销量以便提前调整库存。但是，事务数据通常分布在多个数据库中，它们往往汇总起来联合分析时更有价值。而且，数据通常需要转换为通用格式。</p>
</div>
<div class="paragraph">
<p>所以我们一般不会直接在事务数据库上运行分析查询，而是复制数据到数据仓库。数据仓库是对工作负载进行分析和查询的专用数据存储。为了填充数据仓库，需要将事务数据库系统管理的数据复制过来。将数据复制到数据仓库的过程称为extract-transform-load（ETL）。 ETL过程从事务数据库中提取数据，将其转换为某种通用的结构表示，可能包括验证，值的规范化，编码，重复数据删除（去重）和模式转换，最后将其加载到分析数据库中。 ETL过程可能非常复杂，并且通常需要技术复杂的解决方案来满足性能要求。 ETL过程需要定期运行以保持数据仓库中的数据同步。</p>
</div>
<div class="paragraph">
<p>将数据导入数据仓库后，可以查询和分析数据。通常，在数据仓库上执行两类查询。第一种类型是定期报告查询，用于计算与业务相关的统计信息，比如收入、用户增长或者输出的产量。这些指标汇总到报告中，帮助管理层评估业务的整体健康状况。第二种类型是即席查询，旨在提供特定问题的答案并支持关键业务决策，例如收集统计在投放商业广告上的花费，和获取的相应收入，以评估营销活动的有效性。两种查询由批处理方式由数据仓库执行，如图1-3所示。</p>
</div>
<div class="imageblock">
<div class="content">
<img src="images/spaf_0103.png" alt="spaf 0103">
</div>
</div>
<div class="paragraph">
<p>如今，Apache Hadoop生态系统的组件，已经是许多企业IT基础架构中不可或缺的组成部分。现在的做法不是直接将所有数据都插入关系数据库系统，而是将大量数据（如日志文件，社交媒体或Web点击日志）写入Hadoop的分布式文件系统（HDFS）、S3或其他批量数据存储库，如Apache HBase，以较低的成本提供大容量存储容量。驻留在此类存储系统中的数据可以通过SQL-on-Hadoop引擎查询和处理，例如Apache Hive，Apache Drill或Apache Impala。但是，基础结构与传统数据仓库架构基本相同。</p>
</div>
</div>
</div>
<div class="sect2">
<h3 id="_有状态的流式处理">1.2. 有状态的流式处理</h3>
<div class="paragraph">
<p>日常生活中，所有数据都是作为连续的事件流创建的。比如网站或者移动应用中的用户交互动作，订单的提交，服务器日志或传感器测量数据：所有这些都是事件流。实际上，很少有应用场景，能一次性地生成所需要的完整（有限）数据集。实际应用中更多的是无限事件流。有状态的流处理就是用于处理这种无限事件流的应用程序设计模式，在公司的IT基础设施中有广泛的应用场景。在我们讨论其用例之前，我们将简要介绍有状态流处理的工作原理。</p>
</div>
<div class="paragraph">
<p>如果我们想要无限处理事件流，并且不愿意繁琐地每收到一个事件就记录一次，那这样的应用程序就需要是有状态的，也就是说能够存储和访问中间数据。当应用程序收到一个新事件时，它可以从状态中读取数据，或者向该状态写入数据，总之可以执行任何计算。原则上讲，我们可以在各种不同的地方存储和访问状态，包括程序变量（内存）、本地文件，还有嵌入式或外部数据库。</p>
</div>
<div class="paragraph">
<p>Apache Flink将应用程序状态，存储在内存或者嵌入式数据库中。由于Flink是一个分布式系统，因此需要保护本地状态以防止在应用程序或计算机故障时数据丢失。 Flink通过定期将应用程序状态的一致性检查点（check point）写入远程且持久的存储，来保证这一点。状态、状态一致性和Flink的检查点将在后面的章节中更详细地讨论，但是，现在，图1-4显示了有状态的流式Flink应用程序。</p>
</div>
<div class="imageblock">
<div class="content">
<img src="images/spaf_0104.png" alt="spaf 0104">
</div>
</div>
<div class="paragraph">
<p>有状态的流处理应用程序，通常从事件日志中提取输入事件。事件日志就用来存储和分发事件流。事件被写入持久的仅添加（append-only）日志，这意味着无法更改写入事件的顺序。写入事件日志的流，可以被相同或不同的消费者多次读取。由于日志的仅附加（append-only）属性，事件始终以完全相同的顺序发布给所有消费者。现在已有几种事件日志系统，其中Apache Kafka是最受欢迎的，可以作为开源软件使用，或者是云计算提供商提供的集成服务。</p>
</div>
<div class="paragraph">
<p>在Flink上运行的有状态的流处理应用程序，是很有意思的一件事。在这个架构中，事件日志会按顺序保留输入事件，并且可以按确定的顺序重播它们。如果发生故障，Flink将从先前的检查点（check point）恢复其状态，并重置事件日志上的读取位置，这样就可以恢复整个应用。应用程序将重放（并快进）事件日志中的输入事件，直到它到达流的尾部。此技术一般用于从故障中恢复，但也可用于更新应用程序、修复bug或者修复以前发出的结果，另外还可以用于将应用程序迁移到其他群集，或使用不同的应用程序版本执行A / B测试。</p>
</div>
<div class="paragraph">
<p>如前所述，有状态的流处理是一种通用且灵活的设计架构，可用于许多不同的场景。在下文中，我们提出了三类通常使用有状态流处理实现的应用程序：（1）事件驱动应用程序，（2）数据管道应用程序，以及（3）数据分析应用程序。</p>
</div>
<div class="paragraph">
<p>我们将应用程序分类描述，是为了强调有状态流处理适用于多种业务场景；而实际的应用中，往往会具有以上多种情况的特征。</p>
</div>
<div class="sect3">
<h4 id="_事件驱动应用程序event_driven_applications">1.2.1. 事件驱动应用程序（Event-Driven Applications）</h4>
<div class="paragraph">
<p>事件驱动的应用程序是有状态的流应用程序，它们使用特定的业务逻辑来提取事件流并处理事件。根据业务逻辑，事件驱动的应用程序可以触发诸如发送警报、或电子邮件之类的操作，或者将事件写入向外发送的事件流以供另一个应用程序使用。</p>
</div>
<div class="paragraph">
<p>事件驱动应用程序的典型场景包括：</p>
</div>
<div class="ulist">
<ul>
<li>
<p>实时推荐（例如，在客户浏览零售商网站时推荐产品）</p>
</li>
<li>
<p>行为模式检测或复杂事件处理（例如，用于信用卡交易中的欺诈检测）</p>
</li>
<li>
<p>异常检测（例如，检测侵入计算机网络的尝试</p>
</li>
</ul>
</div>
<div class="paragraph">
<p>事件驱动应用程序是微服务的演变。它们通过事件日志而不是REST调用进行通信，并将应用程序数据保存为本地状态，而不是将其写入外部数据存储区（例如关系数据库或键值数据库）。图1-5显示了由事件驱动的流应用程序组成的服务架构。</p>
</div>
<div class="imageblock">
<div class="content">
<img src="images/spaf_0105.png" alt="spaf 0105">
</div>
</div>
<div class="paragraph">
<p>图1-5中的应用程序通过事件日志连接。一个应用程序将其输出发送到事件日志通道（kafka），另一个应用程序使用其他应用程序发出的事件。事件日志通道将发送者和接收者分离，并提供异步、非阻塞的事件传输。每个应用程序都可以是有状态的，并且可以本地管理自己的状态而无需访问外部数据存储。应用程序也可以单独处理和扩展。</p>
</div>
<div class="paragraph">
<p>与事务性应用程序或微服务相比，事件驱动的应用程序具有多种优势。与读写远程数据库相比，本地状态访问提供了非常好的性能。扩展性和容错性都由流处理器来保证，并且以事件日志作为输入源，应用程序的整个输入数据可以可靠地存储，并且可以确定性地重放。此外，Flink可以将应用程序的状态重置为先前的保存点（save point），从而可以在不丢失状态的情况下更新或重新扩展应用程序。</p>
</div>
<div class="paragraph">
<p>事件驱动的应用程序对运行它们的流处理器有很高的要求，并不是所有流处理器都适合运行事件驱动的应用程序。 API的表现力，以及对状态处理和事件时间支持的程度，决定了可以实现和执行的业务逻辑。这方面取决于流处理器的API，主要看它能提供什么样的状态类型，以及它对事件时间处理的支持程度。此外，精确一次（exactly-once）的状态一致性和扩展应用程序的能力是事件驱动应用程序的基本要求。 Apache Flink符合所有的这些要求，是运行此类应用程序的一个非常好的选择。</p>
</div>
</div>
<div class="sect3">
<h4 id="_数据管道data_pipelines">1.2.2. 数据管道（Data Pipelines）</h4>
<div class="paragraph">
<p>当今的IT架构包括许多不同的数据存储，例如关系型数据库和专用数据库系统、事件日志、分布式文件系统，内存中的缓存和搜索索引。所有这些系统都以不同的格式和数据结构存储数据，为其特定的访问模式提供最佳性能。公司通常将相同的数据存储在多个不同的系统中，以提高数据访问的性能。例如，网上商店中提供的产品的信息，可以存储在交易数据库中，同时也存储在缓存（如redis）和搜索索引（如ES）中。由于数据的这种复制，数据存储必须保持同步。</p>
</div>
<div class="paragraph">
<p>在不同存储系统中同步数据的传统方法是定期ETL作业。但是，它们不能满足当今许多场景的延迟要求。另一种方法是使用事件日志（event log）来发布更新。更新将写入事件日志并由事件日志分发。日志的消费者获取到更新之后，将更新合并到受影响的数据存储中。根据使用情况，传输的数据可能需要标准化、使用外部数据进行扩展，或者在目标数据存储提取之前进行聚合。</p>
</div>
<div class="paragraph">
<p>以较低的延迟，来提取、转换和插入数据是有状态流处理应用程序的另一个常见应用场景。这种类型的应用程序称为数据管道（data pipeline）。数据管道必须能够在短时间内处理大量数据。操作数据管道的流处理器还应具有许多源（source）和接收器（sink）的连接器，以便从各种存储系统读取数据并将数据写入各种存储系统。当然，同样地，Flink完成了所有这些功能。</p>
</div>
</div>
<div class="sect3">
<h4 id="_流分析">1.2.3. 流分析</h4>
<div class="paragraph">
<p>ETL作业定期将数据导入数据存储区，数据的处理是由即席查询（用户自定义查询）或设定好的通常查询来做的。无论架构是基于数据仓库还是基于Hadoop生态系统的组件，这都是批处理。多年来最好的处理方式就是，定期将数据加载到数据分析系统中，但它给分析管道带了的延迟相当大，而且无法避免。</p>
</div>
<div class="paragraph">
<p>根据设定好的时间间隔，可能需要数小时或数天才能将数据点包含在报告中。我们前面已经提到，数据管道可以实现低延迟的ETL，所以在某种程度上，可以通过使用数据管道将数据导入存储区来减少延迟。但是，即使持续不停地进行ETL操作，在用查询来处理事件之前总会有延迟。虽然这种延迟在过去可能是可以接受的，但是今天的应用程序，往往要求必须能够实时收集数据，并立即对其进行操作（例如，在手机游戏中去适应不断变化的条件，或者在电商网站中提供个性化的用户体验）。</p>
</div>
<div class="paragraph">
<p>流式分析应用程序不是等待定期触发，而是连续地提取事件流，并且通过纳入最新事件来更新其计算结果，这个过程是低延迟的。这有些类似于数据库中用于更新视图（views）的技术。通常，流应用程序将其结果存储在支持更新的外部数据存储中，例如数据库或键值（key-value）存储。流分析应用程序的实时更新结果可用于驱动监控仪表板（dashboard）应用程序，如图1-6所示。</p>
</div>
<div class="imageblock">
<div class="content">
<img src="images/spaf_0106.png" alt="spaf 0106">
</div>
</div>
<div class="paragraph">
<p>流分析应用程序最大的优势就是，将每个事件纳入到分析结果所需的时间短得多。除此之外，流分析应用程序还有另一个不太明显的优势。传统的分析管道由几个独立的组件组成，例如ETL过程、存储系统、对于基于Hadoop的环境，还包括用于触发任务（jobs）的数据处理和调度程序。相比之下，如果我们运行一个有状态流应用程序，那么流处理器就会负责所有这些处理步骤，包括事件提取、带有状态维护的连续计算以及更新结果。此外，流处理器可以从故障中恢复，并且具有精确一次（exactly-once）的状态一致性保证，还可以调整应用程序的计算资源。像Flink这样的流处理器还支持事件时间（event-time）处理，这可以保证产生正确和确定的结果，并且能够在很短的时间内处理大量数据。</p>
</div>
<div class="paragraph">
<p>流分析应用程序通常用于：</p>
</div>
<div class="ulist">
<ul>
<li>
<p>监控手机网络的质量分析</p>
</li>
<li>
<p>移动应用中的用户行为</p>
</li>
<li>
<p>实时数据的即席分析</p>
</li>
</ul>
</div>
<div class="paragraph">
<p>虽然我们不在此处介绍，但Flink还提供对流上的分析SQL查询的支持。</p>
</div>
</div>
</div>
<div class="sect2">
<h3 id="_开源流处理的演进">1.3. 开源流处理的演进</h3>
<div class="paragraph">
<p>数据流处理并不是一项新技术。一些最初的研究原型和商业产品可以追溯到20世纪90年代（1990s）。然而，在很大程度上，过去采用的流处理技术是由成熟的开源流处理器驱动的。如今，分布式开源流处理器在不同行业的许多企业中，处理着核心业务应用，比如电商、社交媒体、电信、游戏和银行等。开源软件是这一趋势的主要驱动力，主要原因有两个：</p>
</div>
<div class="ulist">
<ul>
<li>
<p>开源流处理软件是大家每一个人都可以评估和使用的产品。</p>
</li>
<li>
<p>由于许多开源社区的努力，可扩展流处理技术正在迅速成熟和发展</p>
</li>
</ul>
</div>
<div class="paragraph">
<p>仅仅一个Apache软件基金会就支持了十几个与流处理相关的项目。新的分布式流处理项目不断进入开源阶段，并不断增加新的特性和功能。开源社区不断改进其项目的功能，并正在推动流处理的技术边界。我们将简要介绍一下过去，看看开源流处理的起源和今天的状态。</p>
</div>
<div class="sect3">
<h4 id="_流处理的历史">1.3.1. 流处理的历史</h4>
<div class="paragraph">
<p>第一代分布式开源流处理器（2011）专注于具有毫秒延迟的事件处理，并提供了在发生故障时防止事件丢失的保证。这些系统具有相当低级的API，并且对于流应用程序的准确性和结果的一致性，不提供内置支持，因为结果会取决于到达事件的时间和顺序。另外，即使事件没有丢失，也可能不止一次地处理它们。与批处理器相比，第一代开源流处理器牺牲了结果准确性，用来获得更低的延迟。为了让当时的数据处理系统，可以同时提供快速和准确的结果，人们设计了所谓的lambda架构，如图1-7所示。</p>
</div>
<div class="imageblock">
<div class="content">
<img src="images/spaf_0107.png" alt="spaf 0107">
</div>
</div>
<div class="paragraph">
<p>lambda架构增强了传统的批处理架构，其“快速层”（speed layer）由低延迟的流处理器来支持。数据到达之后由流处理器提取出来，并写入批处理存储。流处理器近乎实时地计算近似结果并将它们写入“快速表”（speed table）。批处理器定期处理批量存储中的数据，将准确的结果写入批处理表，并从速度表中删除相应的不准确结果。应用程序会合并快速表中的近似结果和批处理表中的准确结果，然后消费最终的结果。</p>
</div>
<div class="paragraph">
<p>lambda架构现在已经不再是最先进的，但仍在许多地方使用。该体系结构的最初目标是改善原始批处理分析体系结构的高延迟。但是，它有一些明显的缺点。首先，它需要对一个应用程序，做出两个语义上等效的逻辑实现，用于两个独立的、具有不同API的处理系统。其次，流处理器计算的结果只是近似的。第三，lambda架构很难建立和维护。</p>
</div>
<div class="paragraph">
<p>通过在第一代基础上进行改进，下一代分布式开源流处理器（2013）提供了更好的故障保证，并确保在发生故障时，每个输入记录仅对结果产生一次影响（exactly -once）。此外，编程API从相当低级的操作符接口演变为高级API。但是，一些改进（例如更高的吞吐量和更好的故障保证）是以将处理延迟从毫秒增加到几秒为代价的。此外，结果仍然取决于到达事件的时间和顺序。</p>
</div>
<div class="paragraph">
<p>第三代分布式开源流处理器（2015）解决了结果对到达事件的时间和顺序的依赖性。结合精确一次（exactly-once）的故障语义，这一代系统是第一个具有计算一致性和准确结果的开源流处理器。通过基于实际数据来计算结果（“重演”数据），这些系统还能够以与“实时”数据相同的方式处理历史数据。另一个改进是解决了延迟/吞吐量无法同时保证的问题。先前的流处理器仅能提供高吞吐量或者低延迟（其中之一），而第三代系统能够同时提供这两个特性。这一代的流处理器使得lambda架构过时了。当然，这一代流处理以flink为代表。</p>
</div>
<div class="paragraph">
<p>除了目前讨论的特性，例如容错、性能和结果准确性之外，流处理器还不断添加新的操作功能，例如高可用性设置，与资源管理器（如YARN或Kubernetes）的紧密集成，以及能够动态扩展流应用程序。其他功能包括：支持升级应用程序代码，或将作业迁移到其他群集或新版本的流处理器，而不会丢失当前状态。</p>
</div>
</div>
</div>
<div class="sect2">
<h3 id="_flink_简介">1.4. Flink 简介</h3>
<div class="paragraph">
<p>Apache Flink是第三代分布式流处理器，它拥有极富竞争力的功能。它提供准确的大规模流处理，具有高吞吐量和低延迟。特别的是，以下功能使Flink脱颖而出：</p>
</div>
<div class="ulist">
<ul>
<li>
<p>事件时间（event-time）和处理时间（processing-tme）语义。即使对于无序事件流，事件时间（event-time）语义仍然能提供一致且准确的结果。而处理时间（processing-time）语义可用于具有极低延迟要求的应用程序。</p>
</li>
<li>
<p>精确一次（exactly-once）的状态一致性保证。</p>
</li>
<li>
<p>每秒处理数百万个事件，毫秒级延迟。 Flink应用程序可以扩展为在数千个核（cores）上运行。</p>
</li>
<li>
<p>分层API，具有不同的权衡表现力和易用性。本书介绍了DataStream API和过程函数（process function），为常见的流处理操作提供原语，如窗口和异步操作，以及精确控制状态和时间的接口。本书不讨论Flink的关系API，SQL和LINQ风格的Table API。</p>
</li>
<li>
<p>连接到最常用的存储系统，如Apache Kafka，Apache Cassandra，Elasticsearch，JDBC，Kinesis和（分布式）文件系统，如HDFS和S3。</p>
</li>
<li>
<p>由于其高可用的设置（无单点故障），以及与Kubernetes，YARN和Apache Mesos的紧密集成，再加上从故障中快速恢复和动态扩展任务的能力，Flink能够以极少的停机时间7*24全天候运行流应用程序。</p>
</li>
<li>
<p>能够更新应用程序代码并将作业（jobs）迁移到不同的Flink集群，而不会丢失应用程序的状态。</p>
</li>
<li>
<p>详细且可自定义的系统和应用程序指标集合，以提前识别问题并对其做出反应。</p>
</li>
<li>
<p>最后但同样重要的是，Flink也是一个成熟的批处理器。</p>
</li>
</ul>
</div>
<div class="paragraph">
<p>除了这些功能之外，Flink还是一个非常易于开发的框架，因为它易于使用的API。嵌入式执行模式，可以在单个JVM进程中启动应用程序和整个Flink系统，这种模式一般用于在IDE中运行和调试Flink作业。在开发和测试Flink应用程序时，此功能非常有用。</p>
</div>
</div>
</div>
</div>
<div class="sect1">
<h2 id="_流处理基础">2. 流处理基础</h2>
<div class="sectionbody">
<div class="sect2">
<h3 id="_数据流编程简介">2.1. 数据流编程简介</h3>
<div class="paragraph">
<p>在我们深入研究流处理的基础知识之前，让我们来看看在数据流程编程的背景和使用的术语。</p>
</div>
<div class="sect3">
<h4 id="_数据流图dataflow_graph">2.1.1. 数据流图(dataflow graph)</h4>
<div class="paragraph">
<p>顾名思义，数据流程序描述了数据如何在算子之间流动。数据流程序通常表示为有向图，其中节点称为算子，用来表示计算，边表示数据之间的依赖性。算子是数据流程序的基本功能单元。他们从输入消耗数据，对它们执行计算，并生成数据输出用于进一步处理。一个数据流图必须至少有一个数据源和一个数据接收器。</p>
</div>
<div class="imageblock">
<div class="content">
<img src="images/spaf_0201.png" alt="spaf 0201">
</div>
</div>
<div class="paragraph">
<p>像图2-1中的数据流图被称为逻辑流图，因为它们表示了计算逻辑的高级视图。为了执行一个数据流程序，Flink会将逻辑流图转换为物理数据流图，详细说明程序的执行方式。例如，如果我们使用分布式处理引擎，每个算子在不同的物理机器可能有几个并行的任务运行。图2-2显示了图2-1逻辑图的物理数据流图。而在逻辑数据流图中节点表示算子，在物理数据流图中，节点是任务。“Extract hashtags”和“Count”算子有两个并行算子任务，每个算子任务对输入数据的子集执行计算。</p>
</div>
<div class="imageblock">
<div class="content">
<img src="images/spaf_0202.png" alt="spaf 0202">
</div>
</div>
</div>
<div class="sect3">
<h4 id="_数据并行和任务并行">2.1.2. 数据并行和任务并行</h4>
<div class="paragraph">
<p>我们可以以不同方式利用数据流图中的并行性。第一，我们可以对输入数据进行分区，并在数据的子集上并行执行具有相同算子的任务并行。这种类型的并行性被称为数据并行性。数据并行是有用的，因为它允许处理大量数据，并将计算分散到不同的计算节点上。第二，我们可以将不同的算子在相同或不同的数据上并行执行。这种并行性称为任务并行性。使用任务并行性，我们可以更好地利用计算资源。</p>
</div>
</div>
<div class="sect3">
<h4 id="_数据交换策略">2.1.3. 数据交换策略</h4>
<div class="paragraph">
<p>数据交换策略定义了在物理执行流图中如何将数据分配给任务。数据交换策略可以由执行引擎自动选择，具体取决于算子的语义或我们明确指定的语义。在这里，我们简要回顾一些常见的数据交换策略，如图2-3所示。</p>
</div>
<div class="imageblock">
<div class="content">
<img src="images/spaf_0203.png" alt="spaf 0203">
</div>
</div>
<div class="ulist">
<ul>
<li>
<p>前向策略将数据从一个任务发送到接收任务。如果两个任务都位于同一台物理计算机上（这通常由任务调度器确保），这种交换策略可以避免网络通信。</p>
</li>
<li>
<p>广播策略将所有数据发送到算子的所有的并行任务上面去。因为这种策略会复制数据和涉及网络通信，所以代价相当昂贵。</p>
</li>
<li>
<p>基于键控的策略通过Key值(键)对数据进行分区保证具有相同Key的数据将由同一任务处理。在图2-2中，输出“Extract hashtags”算子使用键来分区（hashtag），以便count算子的任务可以正确计算每个\#标签的出现次数。</p>
</li>
<li>
<p>随机策略统一将数据分配到算子的任务中去，以便均匀地将负载分配到不同的计算任务。</p>
</li>
</ul>
</div>
</div>
</div>
<div class="sect2">
<h3 id="_并行处理流数据">2.2. 并行处理流数据</h3>
<div class="paragraph">
<p>既然我们熟悉了数据流编程的基础知识，现在是时候看看这些概念如何应用于并行的处理数据流了。但首先，让我们定义术语数据流：数据流是一个可能无限的事件序列。</p>
</div>
<div class="paragraph">
<p>数据流中的事件可以表示监控数据，传感器测量数据，信用卡交易数据，气象站观测数据，在线用户交互数据，网络搜索数据等。在本节中，我们将学习如何并行处理无限流，使用数据流编程范式。</p>
</div>
<div class="sect3">
<h4 id="_延迟和吞吐量">2.2.1. 延迟和吞吐量</h4>
<div class="paragraph">
<p>流处理程序不同与批处理程序。在评估性能时，要求也有所不同。对于批处理程序，我们通常关心一个作业的总的执行时间，或我们的处理引擎读取输入所需的时间，执行计算，并回写结果。由于流处理程序是连续运行的，输入可能是无界的，所以数据流处理中没有总执行时间的概念。
相反，流处理程序必须尽可能快的提供输入数据的计算结果。我们使用延迟和吞吐量来表征流处理的性能要求。</p>
</div>
</div>
<div class="sect3">
<h4 id="_延迟">2.2.2. 延迟</h4>
<div class="paragraph">
<p>延迟表示处理事件所需的时间。它是接收事件和看到在输出中处理此事件的效果之间的时间间隔。要直观的理解延迟，考虑去咖啡店买咖啡。当你进入咖啡店时，可能还有其他顾客在里面。因此，你排队等候直到轮到你下订单。收银员收到你的付款并通知准备饮料的咖啡师。一旦你的咖啡准备好了，咖啡师会叫你的名字，你可以到柜台拿你的咖啡。服务延迟是从你进入咖啡店的那一刻起，直到你喝上第一口咖啡之间的时间间隔。</p>
</div>
<div class="paragraph">
<p>在数据流中，延迟是以时间为单位测量的，例如毫秒。根据应用程序，我们可能会关心平均延迟，最大延迟或百分位延迟。例如，平均延迟值为10ms意味着处理事件的平均时间在10毫秒内。或者，延迟值为95\% 10ms表示95\%的事件在10ms内处理完毕。平均值隐藏了处理延迟的真实分布，可能会让人难以发现问题。如果咖啡师在准备卡布奇诺之前用完了牛奶，你必须等到他们从供应室带来一些。虽然你可能会因为这么长时间的延迟而生气，但大多数其他客户仍然会感到高兴。</p>
</div>
<div class="paragraph">
<p>确保低延迟对于许多流应用程序来说至关重要，例如欺诈检测，系统警报，网络监控和提供具有严格服务水平协议的服务。低延迟是流处理的关键特性，它实现了我们所谓的实时应用程序。像Apache Flink这样的现代流处理器可以提供低至几毫秒的延迟。相比之下，传统批处理程序延迟通常从几分钟到几个小时不等。在批处理中，首先需要收集事件批次，然后才能处理它们。因此，延迟是受每个批次中最后一个事件的到达时间的限制。所以自然而然取决于批的大小。真正的流处理不会引入这样的人为延迟，因此可以实现真正的低延迟。真的流模型，事件一进入系统就可以得到处理。延迟更密切地反映了在每个事件上必须进行的实际工作。</p>
</div>
</div>
<div class="sect3">
<h4 id="_吞吐量">2.2.3. 吞吐量</h4>
<div class="paragraph">
<p>吞吐量是衡量系统处理能力的指标，也就是处理速率。也就是说，吞吐量告诉我们每个时间单位系统可以处理多少事件。重温咖啡店的例子，如果商店营业时间为早上7点至晚上7点。当天为600个客户提供了服务，它的平均吞吐量将是每小时50个客户。虽然我们希望延迟尽可能低，但我们通常也需要吞吐量尽可能高。</p>
</div>
<div class="paragraph">
<p>吞吐量以每个时间单位系统所能处理的事件数量或操作数量来衡量。值得注意的是，事件处理速率取决于事件到达的速率，低吞吐量并不一定表示性能不佳。
在流式系统中，我们通常希望确保我们的系统可以处理最大的预期事件到达的速率。也就是说，我们主要的关注点在于确定的峰值吞吐量是多少，当系统处于最大负载时性能怎么样。为了更好地理解峰值吞吐量的概念，让我们考虑一个流处理
程序没有收到任何输入的数据，因此没有消耗任何系统资源。当第一个事件进来时，它会尽可能以最小延迟立即处理。例如，如果你是第一个出现在咖啡店的顾客，在早上开门后，你将立即获得服务。理想情况下，您希望此延迟保持不变
，并且独立于传入事件的速率。但是，一旦我们达到使系统资源被完全使用的事件传入速率，我们将不得不开始缓冲事件。在咖啡店里
，午餐后会看到这种情况发生。许多人出现在同一时间，必须排队等候。在此刻，咖啡店系统已达到其峰值吞吐量，进一步增加
事件传入的速率只会导致更糟糕的延迟。如果系统继续以可以处理的速率接收数据，缓冲区可能变为不可用，数据可能会丢失。这种情况是众所周知的
作为背压，有不同的策略来处理它。</p>
</div>
</div>
<div class="sect3">
<h4 id="_延迟与吞吐量的对比">2.2.4. 延迟与吞吐量的对比</h4>
<div class="paragraph">
<p>此时，应该清楚延迟和吞吐量不是独立指标。如果事件需要在处理流水线中待上很长时间，我们不能轻易确保高吞吐量。同样，如果系统容量很小，事件将被缓冲，而且必须等待才能得到处理。</p>
</div>
<div class="paragraph">
<p>让我们重温一下咖啡店的例子来阐明一下延迟和吞吐量如何相互影响。首先，应该清楚存在没有负载时的最佳延迟。也就是说，如果你是咖啡店的唯一客户，会很快得到咖啡。然而，在繁忙时期，客户将不得不排队等待，并且会有延迟增加。另一个影响延迟和吞吐量的因素是处理事件所花费的时间或为每个客户提供服务所花费的时间。想象一下，期间圣诞节假期，咖啡师不得不为每杯咖啡画圣诞老人。这意味着准备一杯咖啡需要的时间会增加，导致每个人花费
更多的时间在等待咖啡师画圣诞老人，从而降低整体吞吐量。</p>
</div>
<div class="paragraph">
<p>那么，你可以同时获得低延迟和高吞吐量吗？或者这是一个无望的努力？我们可以降低得到咖啡的延迟
，方法是：聘请一位更熟练的咖啡师来准备咖啡。在高负载时，这种变化也会增加吞吐量，因为会在相同的时间内为更多的客户提供服务。
实现相同结果的另一种方法是雇用第二个咖啡师来利用并行性。这里的主要想法是降低延迟来增加吞吐量。当然，如果系统可以更快的执行操作，它可以在相同的时间内执行更多操作。
事实上，在流中利用并行性时也会发生这种情况。通过并行处理多个流，在同时处理更多事件的同时降低延迟。</p>
</div>
</div>
</div>
<div class="sect2">
<h3 id="_数据流上的操作">2.3. 数据流上的操作</h3>
<div class="paragraph">
<p>流处理引擎通常提供一组内置操作：摄取(ingest)，转换(transform)和输出流(output)。这些操作可以
结合到数据流图中来实现逻辑流处理程序。在本节中，我们描述最常见的流处理操作。</p>
</div>
<div class="paragraph">
<p>操作可以是无状态的或有状态的。无状态操作不保持任何内部状态。也就是说，事件的处理不依赖于过去看到的任何事件，也没有保留历史。
无状态操作很容易并行化，因为事件可以彼此独立地处理，也独立于事件到达的顺序(和事件到达顺序没有关系)。
而且，在失败的情况下，无状态操作可以是简单的重新启动并从中断处继续处理。相反，
有状态操作可能会维护之前收到的事件的信息。此状态可以通过传入事件更新，也可以用于未来事件的处理逻辑。有状态的流
处理应用程序更难以并行化和以容错的方式来运行，因为状态需要有效的进行分区和在发生故障的情况下可靠地恢复。</p>
</div>
<div class="sect3">
<h4 id="_数据摄入和数据吞吐量">2.3.1. 数据摄入和数据吞吐量</h4>
<div class="paragraph">
<p>数据摄取和数据出口操作允许流处理程序与外部系统通信。数据摄取是操作从外部源获取原始数据并将其转换为其他格式(ETL)。实现数据提取逻辑的运算符被称为数据源。数据源可以从TCP
Socket，文件，Kafka Topic或传感器数据接口中提取数据。数据出口是以适合消费的形式产出到外部系统。执行数据出口的运算符称为数据接收器，包括文件，数据库，消息队列和监控接口。</p>
</div>
</div>
<div class="sect3">
<h4 id="_转换算子">2.3.2. 转换算子</h4>
<div class="imageblock">
<div class="content">
<img src="images/spaf_0204.png" alt="spaf 0204">
</div>
</div>
<div class="paragraph">
<p>转换算子是单遍处理算子，碰到一个事件处理一个事件。这些操作在使用后会消费一个事件，然后对事件数据做一些转换，产生一个新的输出流。转换逻辑可以集成在
操作符中或由UDF函数提供，如图所示图2-4。程序员编写实现自定义计算逻辑。</p>
</div>
<div class="paragraph">
<p>操作符可以接受多个输入流并产生多个输出流。他们还可以通过修改数据流图的结构要么将流分成多个流，要么将流合并为一条流。</p>
</div>
</div>
<div class="sect3">
<h4 id="_滚动聚合">2.3.3. 滚动聚合</h4>
<div class="paragraph">
<p>滚动聚合是一种聚合，例如sum，minimum和maximum，为每个输入事件不断更新。
聚合操作是有状态的，并将当前状态与传入事件一起计算以产生更新的聚合值。请注意能够有效地将当前状态与事件相结合
产生单个值，聚合函数必须是关联的和可交换的。否则，操作符必须存储完整的流数据历史。图2-5显示了最小滚动
聚合。操作符保持当前的最小值和相应地为每个传入的事件来更新最小值。</p>
</div>
<div class="imageblock">
<div class="content">
<img src="images/spaf_0205.png" alt="spaf 0205">
</div>
</div>
</div>
<div class="sect3">
<h4 id="_窗口操作符">2.3.4. 窗口操作符</h4>
<div class="paragraph">
<p>转换和滚动聚合一次处理一个事件产生输出事件并可能更新状态。但是，有些操作必须收集并缓冲数据以计算其结果。
例如，考虑不同流之间的连接或整体聚合这样的操作，例如中值函数。为了在无界流上高效运行这些操作符，我们需要限制
这些操作维护的数据量。在本节中，我们将讨论窗口操作，提供此服务。</p>
</div>
<div class="paragraph">
<p>窗口还可以在语义上实现关于流的比较复杂的查询。我们已经看到了滚动聚合的方式，以聚合值编码整个流的历史数据来为每个事件提供低延迟的结果。
但如果我们只对最近的数据感兴趣的话会怎样？考虑给司机提供实时交通信息的应用程序。这个程序可以使他们避免拥挤的路线。在这种场景下，你想知道某个位置在最近几分钟内是否有事故发生。
另一方面，了解所有发生过的事故在这个应用场景下并没有什么卵用。更重要的是，通过将流历史缩减为单一聚合值，我们将丢失这段时间内数据的变化。例如，我们可能想知道每5分钟有多少车辆穿过
某个路口。</p>
</div>
<div class="paragraph">
<p>窗口操作不断从无限事件流中创建有限的事件集，好让我们执行有限集的计算。通常会基于数据属性或基于时间的窗口来分配事件。
要正确定义窗口运算符语义，我们需要确定如何给窗口分配事件以及对窗口中的元素进行求值的频率是什么样的。
窗口的行为由一组策略定义。窗口策略决定何时创建新的窗口以及要分配的事件属于哪个窗口，以及何时对窗口中的元素进行求值。
而窗口的求值基于触发条件。一旦触发条件得到满足，窗口的内容将会被发送到求值函数，求值函数会将计算逻辑应用于窗口中的元素。
求值函数可以是sum或minimal或自定义的聚合函数。
求值策略可以根据时间或者数据属性计算(例如，在过去五秒内收到的事件或者最近的一百个事件等等)。
接下来，我们描述常见窗口类型的语义。</p>
</div>
<div class="ulist">
<ul>
<li>
<p>滚动窗口是将事件分配到固定大小的不重叠的窗口中。当通过窗口的结尾时，全部事件被发送到求值函数进行处理。基于计数的滚动窗口定义了在触发求值之前需要收集多少事件。图2-6显示了一个基于计数的翻滚窗口，每四个元素一个窗口。基于时间的滚动窗口定义一个时间间隔，包含在此时间间隔内的事件。图2-7显示了基于时间的滚动窗口，将事件收集到窗口中每10分钟触发一次计算。</p>
</li>
</ul>
</div>
<div class="imageblock">
<div class="content">
<img src="images/spaf_0206.png" alt="spaf 0206">
</div>
</div>
<div class="imageblock">
<div class="content">
<img src="images/spaf_0207.png" alt="spaf 0207">
</div>
</div>
<div class="ulist">
<ul>
<li>
<p>滑动窗口将事件分配到固定大小的重叠的窗口中去。因此，事件可能属于多个桶。我们通过提供窗口的长度和滑动距离来定义滑动窗口。滑动距离定义了创建新窗口的间隔。基于滑动计数的窗口，图2-8的长度为四个事件，三个为滑动距离。</p>
</li>
</ul>
</div>
<div class="imageblock">
<div class="content">
<img src="images/spaf_0208.png" alt="spaf 0208">
</div>
</div>
<div class="ulist">
<ul>
<li>
<p>会话窗口在常见的真实场景中很有用，一些场景既不能使用滚动窗口也不能使用滑动窗口。考虑一个分析在线用户行为的应用程序。在应用程序里，我们想把源自同一时期的用户活动或会话事件分组在一起。会话由一系列相邻时间发生的事件组成，接下来有一段时间没有活动。例如，用户在App上浏览一系列的新闻，然后关掉App，那么浏览新闻这段时间的浏览事件就是一个会话。会话窗口事先没有定义窗口的长度，而是取决于数据的实际情况，滚动窗口和滑动窗口无法应用于这个场景。相反，我们需要将同一会话中的事件分配到同一个窗口中去，而不同的会话可能窗口长度不一样。会话窗口会定义一个间隙值来区分不同的会话。间隙值的意思是：用户一段时间内不活动，就认为用户的会话结束了。图2-9显示了一个会话窗口。</p>
</li>
</ul>
</div>
<div class="imageblock">
<div class="content">
<img src="images/spaf_0209.png" alt="spaf 0209">
</div>
</div>
<div class="paragraph">
<p>到目前为止，所有窗口类型都是在整条流上去做窗口操作。但实际上你可能想要将一条流分流成多个逻辑流并定义并行窗口。
例如，如果我们正在接收来自不同传感器的测量结果，那么可能想要在做窗口计算之前按传感器ID对流进行分流操作。
在并行窗口中，每条流都独立于其他流，然后应用了窗口逻辑。图2-10显示了一个基于计数的长度为2的并行滚动窗口，根据事件颜色分流。</p>
</div>
<div class="imageblock">
<div class="content">
<img src="images/spaf_0210.png" alt="spaf 0210">
</div>
</div>
<div class="paragraph">
<p>在流处理中，窗口操作与两个主要概念密切相关：时间语义和状态管理。时间也许是流处理最重要的方面。即使低延迟是流处理的一个有吸引力的特性，它的真正价值不仅仅是快速分析。真实世界的系统，网络和通信渠道远非完美，流数据经常被推迟或无序(乱序)到达。理解如何在这种条件下提供准确和确定的结果是至关重要的。
更重要的是，流处理程序可以按原样处理事件制作的也应该能够处理相同的历史事件方式，从而实现离线分析甚至时间旅行分析。
当然，前提是我们的系统可以保存状态，因为可能有故障发生。到目前为止，我们看到的所有窗口类型在产生结果前都需要保存之前的数据。实际上，如果我们想计算任何指标，即使是简单的计数，我们也需要保存状态。考虑到流处理程序可能会运行几天，几个月甚至几年，我们需要确保状态可以在发生故障的情况下可靠地恢复。
并且即使程序崩溃，我们的系统也能保证计算出准确的结果。本章，我们将在流处理应用可能发生故障的语境下，深入探讨时间和状态的概念。</p>
</div>
</div>
</div>
<div class="sect2">
<h3 id="_时间语义">2.4. 时间语义</h3>
<div class="paragraph">
<p>在本节中，我们将介绍时间语义，并描述流中不同的时间概念。我们将讨论流处理器在乱序事件流的情况下如何提供准确的计算结果，以及我们如何处理历史事件流，如何在流中进行时间旅行。</p>
</div>
<div class="sect3">
<h4 id="_在流处理中一分钟代表什么">2.4.1. 在流处理中一分钟代表什么？</h4>
<div class="paragraph">
<p>在处理可能是无限的事件流（包含了连续到达的事件），时间成为流处理程序的核心方面。假设我们想要连续的计算结果，可能每分钟就要计算一次。在我们的流处理程序上下文中，一分钟的意思是什么？</p>
</div>
<div class="paragraph">
<p>考虑一个程序需要分析一款移动端的在线游戏的用户所产生的事件流。游戏中的用户分了组，而应用程序将收集每个小组的活动数据，基于小组中的成员多快达到了游戏设定的目标，然后在游戏中提供奖励。例如额外的生命和用户升级。例如，如果一个小组中的所有用户在一分钟之内都弹出了500个泡泡，他们将升一级。Alice是一个勤奋的玩家，她在每天早晨的通勤时间玩游戏。问题在于Alice住在柏林，并且乘地铁去上班。而柏林的地铁手机信号很差。我们设想一个这样的场景，Alice当她的手机连上网时，开始弹泡泡，然后游戏会将数据发送到我们编写的应用程序中，这时地铁突然进入了隧道，她的手机也断网了。Alice还在玩这个游戏，而产生的事件将会缓存在手机中。当地铁离开隧道，Alice的手机又在线了，而手机中缓存的游戏事件将发送到应用程序。我们的应用程序应该如何处理这些数据？在这个场景中一分钟的意思是什么？这个一分钟应该包含Alice离线的那段时间吗？下图展示了这个问题。</p>
</div>
<div class="imageblock">
<div class="content">
<img src="images/spaf_0211.png" alt="spaf 0211">
</div>
</div>
<div class="paragraph">
<p>在线手游是一个简单的场景，展示了应用程序的运算应该取决于事件实际发生的时间，而不是应用程序收到事件的时间。如果我们按照应用程序收到事件的时间来进行处理的话，最糟糕的后果就是，Alice和她的朋友们再也不玩这个游戏了。但是还有很多时间语义非常关键的应用程序，我们需要保证时间语义的正确性。如果我们只考虑我们在一分钟之内收到了多少数据，我们的结果会变化，因为结果取决于网络连接的速度或处理的速度。相反，定义一分钟之内的事件数量，这个一分钟应该是数据本身的时间。</p>
</div>
<div class="paragraph">
<p>在Alice的这个例子中，流处理程序可能会碰到两个不同的时间概念：处理时间和事件时间。我们将在接下来的部分，讨论这两个概念。</p>
</div>
</div>
<div class="sect3">
<h4 id="_处理时间">2.4.2. 处理时间</h4>
<div class="paragraph">
<p>处理时间是处理流的应用程序的机器的本地时钟的时间（墙上时钟）。处理时间的窗口包含了一个时间段内来到机器的所有事件。这个时间段指的是机器的墙上时钟。如下图所示，在Alice的这个例子中，处理时间窗口在Alice的手机离线的情况下，时间将会继续行走。但这个处理时间窗口将不会收集Alice的手机离线时产生的事件。</p>
</div>
<div class="imageblock">
<div class="content">
<img src="images/spaf_0212.png" alt="spaf 0212">
</div>
</div>
</div>
<div class="sect3">
<h4 id="_事件时间">2.4.3. 事件时间</h4>
<div class="paragraph">
<p>事件时间是流中的事件实际发生的时间。事件时间基于流中的事件所包含的时间戳。通常情况下，在事件进入流处理程序前，事件数据就已经包含了时间戳。下图展示了事件时间窗口将会正确的将事件分发到窗口中去。可以如实反应事情是怎么发生的。即使事件可能存在延迟。</p>
</div>
<div class="imageblock">
<div class="content">
<img src="images/spaf_0213.png" alt="spaf 0213">
</div>
</div>
<div class="paragraph">
<p>事件时间使得计算结果的过程不需要依赖处理数据的速度。基于事件时间的操作是可以预测的，而计算结果也是确定的。无论流处理程序处理流数据的速度快或是慢，无论事件到达流处理程序的速度快或是慢，事件时间窗口的计算结果都是一样的。</p>
</div>
<div class="paragraph">
<p>可以处理迟到的事件只是我们使用事件时间所克服的一个挑战而已。普遍存在的事件乱序问题可以使用事件时间得到解决。考虑和Alice玩同样游戏的Bob，他恰好和Alice在同一趟地铁上。Alice和Bob虽然玩的游戏一样，但他们的手机信号是不同的运营商提供的。当Alice的手机没信号时，Bob的手机依然有信号，游戏数据可以正常发送出去。</p>
</div>
<div class="paragraph">
<p>如果使用事件时间，即使碰到了事件乱序到达的情况，我们也可以保证结果的正确性。还有，当我们在处理可以重播的流数据时，由于时间戳的确定性，我们可以快进过去。也就是说，我们可以重播一条流，然后分析历史数据，就好像流中的事件是实时发生一样。另外，我们可以快进历史数据来使我们的应用程序追上现在的事件，然后应用程序仍然是一个实时处理程序，而且业务逻辑不需要改变。</p>
</div>
</div>
<div class="sect3">
<h4 id="_水位线watermarks">2.4.4. 水位线（Watermarks）</h4>
<div class="paragraph">
<p>在我们对事件时间窗口的讨论中，我们忽略了一个很重要的方面：我们应该怎样去决定何时触发事件时间窗口的计算？也就是说，在我们可以确定一个时间点之前的所有事件都已经到达之前，我们需要等待多久？我们如何知道事件是迟到的？在分布式系统无法准确预测行为的现实条件下，以及外部组件所引发的事件的延迟，以上问题并没有准确的答案。在本小节中，我们将会看到如何使用水位线来设置事件时间窗口的行为。</p>
</div>
<div class="paragraph">
<p>水位线是全局进度的度量标准。系统可以确信在一个时间点之后，不会有早于这个时间点发生的事件到来了。本质上，水位线提供了一个逻辑时钟，这个逻辑时钟告诉系统当前的事件时间。当一个运算符接收到含有时间T的水位线时，这个运算符会认为早于时间T的发生的事件已经全部都到达了。对于事件时间窗口和乱序事件的处理，水位线非常重要。运算符一旦接收到水位线，运算符会认为一段时间内发生的所有事件都已经观察到，可以触发针对这段时间内所有事件的计算了。</p>
</div>
<div class="paragraph">
<p>水位线提供了一种结果可信度和延时之间的妥协。激进的水位线设置可以保证低延迟，但结果的准确性不够。在这种情况下，迟到的事件有可能晚于水位线到达，我们需要编写一些代码来处理迟到事件。另一方面，如果水位线设置的过于宽松，计算的结果准确性会很高，但可能会增加流处理程序不必要的延时。</p>
</div>
<div class="paragraph">
<p>在很多真实世界的场景里面，系统无法获得足够的知识来完美的确定水位线。在手游这个场景中，我们无法得知一个用户离线时间会有多长，他们可能正在穿越一条隧道，可能正在乘飞机，可能永远不会再玩儿了。水位线无论是用户自定义的或者是自动生成的，在一个分布式系统中追踪全局的时间进度都不是很容易。所以仅仅依靠水位线可能并不是一个很好的主意。流处理系统还需要提供一些机制来处理迟到的元素（在水位线之后到达的事件）。根据应用场景，我们可能需要把迟到事件丢弃掉，或者写到日志里，或者使用迟到事件来更新之前已经计算好的结果。</p>
</div>
</div>
<div class="sect3">
<h4 id="_处理时间_vs_事件时间">2.4.5. 处理时间 vs 事件时间</h4>
<div class="paragraph">
<p>大家可能会有疑问，既然事件时间已经可以解决我们的所有问题，为什么我们还要对比这两个时间概念？真相是，处理时间在很多情况下依然很有用。处理时间窗口将会带来理论上最低的延迟。因为我们不需要考虑迟到事件以及乱序事件，所以一个窗口只需要简单的缓存窗口内的数据即可，一旦机器时间超过指定的处理时间窗口的结束时间，就会触发窗口的计算。所以对于一些处理速度比结果准确性更重要的流处理程序，处理时间就派上用场了。另一个应用场景是，当我们需要在真实的时间场景下，周期性的报告结果时，同时不考虑结果的准确性。一个例子就是一个实时监控的仪表盘，负责显示当事件到达时立即聚合的结果。最后，处理时间窗口可以提供流本身数据的忠实表达，对于一些案例可能是很必要的特性。例如我们可能对观察流和对每分钟事件的计数（检测可能存在的停电状况）很感兴趣。简单的说，处理时间提供了低延迟，同时结果也取决于处理速度，并且也不能保证确定性。另一方面，事件时间保证了结果的确定性，同时还可以使我们能够处理迟到的或者乱序的事件流。</p>
</div>
</div>
</div>
<div class="sect2">
<h3 id="_状态和持久化模型">2.5. 状态和持久化模型</h3>
<div class="paragraph">
<p>我们现在转向另一个对于流处理程序非常重要的话题：状态。在数据处理中，状态是普遍存在的。任何稍微复杂一点的计算，都涉及到状态。为了产生计算结果，一个函数在一段时间内的一定数量的事件上来累加状态（例如，聚合计算或者模式匹配）。有状态的运算符使用输入的事件以及内部保存的状态来计算得到输出。例如，一个滚动聚合运算符需要输出这个运算符所观察到的所有事件的累加和。这个运算符将会在内部保存当前观察到的所有事件的累加和，同时每输入一个事件就更新一次累加和的计算结果。相似的，当一个运算符检测到一个“高温”事件紧接着十分钟以内检测到一个“烟雾”事件时，将会报警。直到运算符观察到一个“烟雾”事件或者十分钟的时间段已经过去，这个运算符需要在内部状态中一直保存着“高温”事件。</p>
</div>
<div class="paragraph">
<p>当我们考虑一下使用批处理系统来分析一个无界数据集时，会发现状态的重要性显而易见。在现代流处理器兴起之前，处理无界数据集的一个通常做法是将输入的事件攒成微批，然后交由批处理器来处理。当一个任务结束时，计算结果将被持久化，而所有的运算符状态就丢失了。一旦一个任务在计算下一个微批次的数据时，这个任务是无法访问上一个任务的状态的（都丢掉了）。这个问题通常使用将状态代理到外部系统（例如数据库）的方法来解决。相反，在一个连续不间断运行的流处理任务中，事件的状态是一直存在的，我们可以将状态暴露出来作为编程模型中的一等公民。当然，我们的确可以使用外部系统来管理流的状态，即使这个解决方案会带来额外的延迟。</p>
</div>
<div class="paragraph">
<p>由于流处理运算符默认处理的是无界数据流。所以我们必须要注意不要让内部状态无限的增长。为了限制状态的大小，运算符通常情况下会保存一些之前所观察到的事件流的总结或者概要。这个总结可能是一个计数值，一个累加和，或者事件流的采样，窗口的缓存操作，或者是一个自定义的数据结构，这个数据结构用来保存数据流中感兴趣的一些特性。</p>
</div>
<div class="paragraph">
<p>我们可以想象的到，支持有状态的运算符可能会碰到一些实现上的挑战：</p>
</div>
<div class="paragraph">
<p><strong>状态管理</strong></p>
</div>
<div class="paragraph">
<p>系统需要高效的管理状态，并保证针对状态的并发更新，不会产生竞争条件（race condition）。</p>
</div>
<div class="paragraph">
<p><strong>状态分区</strong></p>
</div>
<div class="paragraph">
<p>并行会带来复杂性。因为计算结果同时取决于已经保存的状态和输入的事件流。幸运的是，大多数情况下，我们可以使用Key来对状态进行分区，然后独立的管理每一个分区。例如，当我们处理一组传感器的测量事件流时，我们可以使用分区的运算符状态来针对不同的传感器独立的保存状态。</p>
</div>
<div class="paragraph">
<p><strong>状态恢复</strong></p>
</div>
<div class="paragraph">
<p>第三个挑战是有状态的运算符如何保证状态可以恢复，即使出现任务失败的情况，计算也是正确的。</p>
</div>
<div class="paragraph">
<p>下一节，我们将讨论任务失败和计算结果的保证。</p>
</div>
<div class="sect3">
<h4 id="_任务失败">2.5.1. 任务失败</h4>
<div class="paragraph">
<p>流任务中的运算符状态是很宝贵的，也需要抵御任务失败带来的问题。如果在任务失败的情况下，状态丢失的话，在任务恢复以后计算的结果将是不正确的。流任务会连续不断的运行很长时间，而状态可能已经收集了几天甚至几个月。在失败的情况下，重新处理所有的输入并重新生成一个丢失的状态，将会很浪费时间，开销也很大。</p>
</div>
<div class="paragraph">
<p>在本章开始时，我们看到如何将流的编程建模成数据流模型。在执行之前，流程序将会被翻译成物理层数据流图，物理层数据流图由连接的并行任务组成，而一个并行任务运行一些运算符逻辑，消费输入流数据，并为其他任务产生输出流数据。真实场景下，可能有数百个这样的任务并行运行在很多的物理机器上。在长时间的运行中，流任务中的任意一个任务在任意时间点都有可能失败。我们如何保证任务的失败能被正确的处理，以使任务能继续的运行下去呢？事实上，我们可能希望我们的流处理器不仅能在任务失败的情况下继续处理数据，还能保证计算结果的正确性以及运算符状态的安全。我们在本小节来讨论这些问题。</p>
</div>
<div class="sect4">
<h5 id="_什么是任务失败">什么是任务失败？</h5>
<div class="paragraph">
<p>对于流中的每一个事件，一个处理任务分为以下步骤：（1）接收事件，并将事件存储在本地的缓存中；（2）可能会更新内部状态；（3）产生输出记录。这些步骤都能失败，而系统必须对于在失败的场景下如何处理有清晰的定义。如果任务在第一步就失败了，事件会丢失吗？如果当更新内部状态的时候任务失败，那么内部状态会在任务恢复以后更新吗？在以上这些场景中，输出是确定性的吗？</p>
</div>
<div class="paragraph">
<p>在批处理场景下，所有的问题都不是问题。因为我们可以很方便的重新计算。所以不会有事件丢失，状态也可以得到完全恢复。在流的世界里，处理失败不是一个小问题。流系统在失败的情况下需要保证结果的准确性。接下来，我们需要看一下现代流处理系统所提供的一些保障，以及实现这些保障的机制。</p>
</div>
</div>
<div class="sect4">
<h5 id="_结果的保证">结果的保证</h5>
<div class="paragraph">
<p>当我们讨论保证计算的结果时，我们的意思是流处理器的内部状态需要保证一致性。也就是说我们关心的是应用程序的代码在故障恢复以后看到的状态值是什么。要注意保证应用程序状态的一致性并不是保证应用程序的输出结果的一致性。一旦输出结果被持久化，结果的准确性就很难保证了。除非持久化系统支持事务。</p>
</div>
<div class="paragraph">
<p><strong>AT-MOST-ONCE</strong></p>
</div>
<div class="paragraph">
<p>当任务故障时，最简单的做法是什么都不干，既不恢复丢失的状态，也不重播丢失的事件。At-most-once语义的含义是最多处理一次事件。换句话说，事件可以被丢弃掉，也没有任何操作来保证结果的准确性。这种类型的保证也叫“没有保证”，因为一个丢弃掉所有事件的系统其实也提供了这样的保障。没有保障听起来是一个糟糕的主意，但如果我们能接受近似的结果，并且希望尽可能低的延迟，那么这样也挺好。</p>
</div>
<div class="paragraph">
<p><strong>AT-LEAST-ONCE</strong></p>
</div>
<div class="paragraph">
<p>在大多数的真实应用场景，我们希望不丢失事件。这种类型的保障成为at-least-once，意思是所有的事件都得到了处理，而且一些事件还可能被处理多次。如果结果的正确性仅仅依赖于数据的完整性，那么重复处理是可以接受的。例如，判断一个事件是否在流中出现过，at-least-once这样的保证完全可以正确的实现。在最坏的情况下，我们多次遇到了这个事件。而如果我们要对一个特定的事件进行计数，计算结果就可能是错误的了。</p>
</div>
<div class="paragraph">
<p>为了保证在at-least-once语义的保证下，计算结果也能正确。我们还需要另一套系统来从数据源或者缓存中重新播放数据。持久化的事件日志系统将会把所有的事件写入到持久化存储中。所以如果任务发生故障，这些数据可以重新播放。还有一种方法可以获得同等的效果，就是使用结果承认机制。这种方法将会把每一条数据都保存在缓存中，直到数据的处理等到所有的任务的承认。一旦得到所有任务的承认，数据将被丢弃。</p>
</div>
<div class="paragraph">
<p><strong>EXACTLY-ONCE</strong></p>
</div>
<div class="paragraph">
<p>恰好处理一次是最严格的保证，也是最难实现的。恰好处理一次语义不仅仅意味着没有事件丢失，还意味着针对每一个数据，内部状态仅仅更新一次。本质上，恰好处理一次语义意味着我们的应用程序可以提供准确的结果，就好像从未发生过故障。</p>
</div>
<div class="paragraph">
<p>提供恰好处理一次语义的保证必须有至少处理一次语义的保证才行，同时还需要数据重放机制。另外，流处理器还需要保证内部状态的一致性。也就是说，在故障恢复以后，流处理器应该知道一个事件有没有在状态中更新。事务更新是达到这个目标的一种方法，但可能引入很大的性能问题。Flink使用了一种轻量级快照机制来保证恰好处理一次语义。</p>
</div>
<div class="paragraph">
<p><strong>端到端恰好处理一次</strong></p>
</div>
<div class="paragraph">
<p>目前我们看到的一致性保证都是由流处理器实现的，也就是说都是在Flink流处理器内部保证的。而在真实世界中，流处理应用除了流处理器以外还包含了数据源（例如Kafka）和持久化系统。端到端的一致性保证意味着结果的正确性贯穿了整个流处理应用的始终。每一个组件都保证了它自己的一致性。而整个端到端的一致性级别取决于所有组件中一致性最弱的组件。要注意的是，我们可以通过弱一致性来实现更强的一致性语义。例如，当任务的操作具有幂等性时，比如流的最大值或者最小值的计算。在这种场景下，我们可以通过最少处理一次这样的一致性来实现恰好处理一次这样的最高级别的一致性。</p>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="sect1">
<h2 id="_flink运行架构">3. Flink运行架构</h2>
<div class="sectionbody">
<div class="sect2">
<h3 id="_系统架构">3.1. 系统架构</h3>
<div class="paragraph">
<p>Flink是一个用于有状态的并行数据流处理的分布式系统。它由多个进程构成，这些进程一般会分布运行在不同的机器上。对于分布式系统来说，面对的常见问题有：集群中资源的分配和管理、进程协调调度、持久化和高可用的数据存储，以及故障恢复。</p>
</div>
<div class="paragraph">
<p>对于这些分布式系统的经典问题，业内已有比较成熟的解决方案和服务。所以Flink并不会自己去处理所有的问题，而是利用了现有的集群架构和服务，这样它就可以把精力集中在核心工作——分布式数据流处理上了。Flink与一些集群资源管理工具有很好的集成，比如Apache Mesos、YARN和Kubernetes；同时，也可以配置为独立（stand-alone）集群运行。Flink自己并不提供持久化的分布式存储，而是直接利用了已有的分布式文件系统（比如HDFS）或者对象存储（比如S3）。对于高可用的配置，Flink需要依靠Apache ZooKeeper来完成。</p>
</div>
<div class="paragraph">
<p>在本节中，我们将介绍Flink的不同组件，以及在运行程序时它们如何相互作用。我们会讨论部署Flink应用程序的两种模式，并且了解每种模式下分发和执行任务的方式。最后，我们还会解释一下Flink的高可用性模式是如何工作的。</p>
</div>
<div class="sect3">
<h4 id="_flink运行时组件">3.1.1. Flink运行时组件</h4>
<div class="paragraph">
<p>Flink运行时架构主要包括四个不同的组件，它们会在运行流处理应用程序时协同工作：作业管理器（JobManager）、资源管理器（ResourceManager）、任务管理器（TaskManager），以及分发器（Dispatcher）。因为Flink是用Java和Scala实现的，所以所有组件都会运行在Java虚拟机（JVMs）上。每个组件的职责如下：</p>
</div>
<div class="ulist">
<ul>
<li>
<p>作业管理器（JobManager）是控制一个应用程序执行的主进程，也就是说，每个应用程序都会被一个不同的JobManager所控制执行。JobManager会先接收到要执行的应用程序。这个应用程序会包括：作业图（JobGraph）、逻辑数据流图（logical dataflow graph）和打包了所有的类、库和其它资源的JAR包。JobManager会把JobGraph转换成一个物理层面的数据流图，这个图被叫做“执行图”（ExecutionGraph），包含了所有可以并发执行的任务。JobManager会向资源管理器（ResourceManager）请求执行任务必要的资源，也就是任务管理器（TaskManager）上的插槽（slot）。一旦它获取到了足够的资源，就会将执行图分发到真正运行它们的TaskManager上。而在运行过程中，JobManager会负责所有需要中央协调的操作，比如说检查点（checkpoints）的协调。</p>
</li>
<li>
<p>ResourceManager主要负责管理任务管理器（TaskManager）的插槽（slot），TaskManger插槽是Flink中定义的处理资源单元。Flink为不同的环境和资源管理工具提供了不同资源管理器（ResourceManager），比如YARN、Mesos、K8s，以及standalone部署。当JobManager申请插槽资源时，ResourceManager会将有空闲插槽的TaskManager分配给JobManager。如果ResourceManager没有足够的插槽来满足JobManager的请求，它还可以向资源提供平台发起会话，以提供启动TaskManager进程的容器。另外，ResourceManager还负责终止空闲的TaskManager，释放计算资源。</p>
</li>
<li>
<p>任务管理器（TaskManager）是Flink中的工作进程。通常在Flink中会有多个TaskManager运行，每一个TaskManager都包含了一定数量的插槽（slots）。插槽的数量限制了TaskManager能够执行的任务数量。启动之后，TaskManager会向资源管理器注册它的插槽；收到资源管理器的指令后，TaskManager就会将一个或者多个插槽提供给JobManager调用。JobManager就可以向插槽分配任务（tasks）来执行了。在执行过程中，一个TaskManager可以跟其它运行同一应用程序的TaskManager交换数据。任务的执行和插槽的概念会在“任务执行”一节做具体讨论。</p>
</li>
<li>
<p>分发器（Dispatcher）可以跨作业运行，它为应用提交提供了REST接口。当一个应用被提交执行时，分发器就会启动并将应用移交给一个JobManager。由于是REST接口，所以Dispatcher可以作为集群的一个HTTP接入点，这样就能够不受防火墙阻挡。Dispatcher也会启动一个Web UI，用来方便地展示和监控作业执行的信息。Dispatcher在架构中可能并不是必需的，这取决于应用提交运行的方式。</p>
</li>
</ul>
</div>
<div class="imageblock">
<div class="content">
<img src="images/spaf_0301.png" alt="spaf 0301">
</div>
</div>
<div class="admonitionblock note">
<table>
<tr>
<td class="icon">
<i class="fa icon-note" title="Note"></i>
</td>
<td class="content">
上图是从一个较为高层级的视角，来看应用中各组件的交互协作。如果部署的集群环境不同（例如YARN，Mesos，Kubernetes，standalone等），其中一些步骤可以被省略，或是有些组件会运行在同一个JVM进程中。
</td>
</tr>
</table>
</div>
</div>
<div class="sect3">
<h4 id="_应用部署">3.1.2. 应用部署</h4>
<div class="paragraph">
<p>Flink应用程序可以用以下两种不同的方式部署：</p>
</div>
<div class="paragraph">
<p><strong>框架（Framework）方式</strong></p>
</div>
<div class="paragraph">
<p>在这个模式下，Flink应用被打包成一个Jar文件，并由客户端提交给一个运行服务（running service）。这个服务可以是一个Flink的Dispatcher，也可以是一个Flink的JobManager，或是Yarn的ResourceManager。如果application被提交给一个JobManager，则它会立即开始执行这个application。如果application被提交给了一个Dispatcher，或是Yarn ResourceManager，则它会启动一个JobManager，然后将application交给它，再由JobManager开始执行此应用。</p>
</div>
<div class="paragraph">
<p><strong>库（Library）方式</strong></p>
</div>
<div class="paragraph">
<p>在这个模式下，Flink Application 会被打包在一个容器（container） 镜像里，例如一个Docker 镜像。此镜像包含了运行JobManager和ResourceManager的代码。当一个容器从镜像启动后，它会自动启动ResourceManager和JobManager，并提交打包好的应用。另一种方法是：将应用打包到镜像后，只用于部署TaskManager容器。从镜像启动的容器会自动启动一个TaskManager，然后连接ResourceManager并注册它的slots。这些镜像的启动以及失败重启，通常都会由一个外部的资源管理器管理（比如Kubernetes）。</p>
</div>
<div class="paragraph">
<p>框架模式遵循了传统的任务提交方式，从客户端提交到Flink运行服务。而在库模式下，没有运行的Flink服务。它是将Flink作为一个库，与应用程序一同打包到了一个容器镜像。这种部署方式在微服务架构中较为常见。我们会在“运行管理流式应用程序”一节对这个话题做详细讨论。</p>
</div>
</div>
<div class="sect3">
<h4 id="_任务执行">3.1.3. 任务执行</h4>
<div class="paragraph">
<p>一个TaskManager可以同时执行多个任务（tasks）。这些任务可以是同一个算子（operator）的子任务（数据并行），也可以是来自不同算子的（任务并行），甚至可以是另一个不同应用程序的（作业并行）。TaskManager提供了一定数量的处理插槽（processing slots），用于控制可以并行执行的任务数。一个slot可以执行应用的一个分片，也就是应用中每一个算子的一个并行任务。图3-2展示了TaskManagers，slots，tasks以及operators之间的关系：</p>
</div>
<div class="imageblock">
<div class="content">
<img src="images/spaf_0302.png" alt="spaf 0302">
</div>
</div>
<div class="paragraph">
<p>最左边是一个“作业图”（JobGraph），包含了5个算子——它是应用程序的非并行表示。其中算子A和C是数据源（source），E是输出端（sink）。C和E并行度为2，而其他的算子并行度为4。因为最高的并行度是4，所以应用需要至少四个slot来执行任务。现在有两个TaskManager，每个又各有两个slot，所以我们的需求是满足的。JobManager将JobGraph转化为“执行图”（ExecutionGraph），并将任务分配到四个可用的slot上。对于有4个并行任务的算子，它的task会分配到每个slot上。而对于并行度为2的operator C和E，它们的任务被分配到slot 1.1、2.1 以及 slot 1.2、2.2。将tasks调度到slots上，可以让多个tasks跑在同一个TaskManager内，也就可以是的tasks之间的数据交换更高效。然而将太多任务调度到同一个TaskManager上会导致TaskManager过载，继而影响效率。之后我们会在“控制任务调度”一节继续讨论如何控制任务的调度。</p>
</div>
<div class="paragraph">
<p>TaskManager在同一个JVM中以多线程的方式执行任务。线程较进程会更轻量级，但是线程之间并没有对任务进行严格隔离。所以，单个任务的异常行为有可能会导致整个TaskManager进程挂掉，当然也同时包括运行在此进程上的所有任务。通过为每个TaskManager配置单独的slot，就可以将应用在TaskManager上相互隔离开来。TaskManager内部有多线程并行的机制，而且在一台主机上可以部署多个TaskManager，所以Flink在资源配置上非常灵活，在部署应用时可以充分权衡性能和资源的隔离。我们将会在第九章对Flink集群的配置和搭建继续做详细讨论。</p>
</div>
</div>
<div class="sect3">
<h4 id="_高可用配置">3.1.4. 高可用配置</h4>
<div class="paragraph">
<p>流式应用程序一般被设计为7 x 24小时运行。所以很重要的一点是：即使出现了进程挂掉的情况，应用仍需要继续保持运行。为了从故障恢复，系统首先需要重启进程、然后重启应用并恢复它的状态。接下来，我们就来了解Flink如何重启失败的进程。</p>
</div>
<div class="paragraph">
<p><strong>TaskManager故障</strong></p>
</div>
<div class="paragraph">
<p>如前所述，Flink需要足够数目的slot，来执行一个应用的所有任务。假设一个Flink环境有4个TaskManager，每个提供2个插槽，那么流应用程序执行的最高并行度为8。如果其中一个TaskManager挂掉了，那么可用的slots会降到6。在这种情况下，JobManager会请求ResourceManager提供更多的slots。如果此请求无法满足——例如应用跑在一个standalone集群——那么JobManager在有足够的slots之前，无法重启应用。应用的重启策略决定了JobManager的重启频率，以及两次重启尝试之间的时间间隔。</p>
</div>
<div class="paragraph">
<p><strong>JobManager故障</strong></p>
</div>
<div class="paragraph">
<p>比TaskManager故障更严重的问题是JobManager故障。JobManager控制整个流应用程序的执行，并维护执行中的元数据——例如指向已完成检查点的指针。若是对应的JobManager挂掉，则流程序无法继续运行。所以这就导致在Flink应用中，JobManager是单点故障。为了解决这个问题，Flink提供了高可用模式。在原先的JobManager挂掉后，可以将一个作业的状态和元数据迁移到另一个JobManager，并继续执行。</p>
</div>
<div class="paragraph">
<p>Flink的高可用模式基于Apache ZooKeeper，我们知道，ZooKeeper是用来管理需要协调和共识的分布式服务的系统。Flink主要利用ZooKeeper来进行领导者（leader）的选举，并把它作为一个高可用和持久化的数据存储。当在高可用模式下运行时，JobManager会将JobGraph以及所有需要的元数据（例如应用程序的jar文件），写入到一个远程的持久化存储系统中。而且，JobManager会将指向存储位置的指针，写入到ZooKeeper的数据存储中。在执行一个应用的过程中，JobManager会接收每个独立任务检查点的状态句柄（也就是存储位置）。当一个检查点完成时（所有任务已经成功地将它们的状态写入到远程存储）， JobManager把状态句柄写入远程存储，并将指向这个远程存储的指针写入ZooKeeper。这样，一个JobManager挂掉之后再恢复，所需要的所有数据信息已经都保存在了远程存储，而ZooKeeper里存有指向此存储位置的指针。图3-3描述了这个设计：</p>
</div>
<div class="imageblock">
<div class="content">
<img src="images/spaf_0303.png" alt="spaf 0303">
</div>
</div>
<div class="paragraph">
<p>当一个JobManager失败，所有属于这个应用的任务都会自动取消。一个新的JobManager接管工作，会执行以下操作：</p>
</div>
<div class="ulist">
<ul>
<li>
<p>从ZooKeeper请求存储位置（storage location），从远端存储获取JobGraph，Jar文件，以及应用最近一次检查点（checkpoint）的状态句柄（state handles）</p>
</li>
<li>
<p>从ResourceManager请求slots，用来继续运行应用</p>
</li>
<li>
<p>重启应用，并将所有任务的状态，重设为最近一次已完成的检查点</p>
</li>
</ul>
</div>
<div class="paragraph">
<p>如果我们是在容器环境里运行应用（如Kubernetes），故障的JobManager或TaskManager 容器通常会由容器服务自动重启。当运行在YARN或Mesos之上时，JobManager或TaskManager进程会由Flink的保留进程自动触发重启。而在standalone模式下，Flink并未提供重启故障进程的工具。所以，此模式下我们可以增加备用（standby）的 JobManager和TaskManager，用于接管故障的进程。我们将会在“高可用配置”一节中做进一步讨论。</p>
</div>
</div>
</div>
<div class="sect2">
<h3 id="_flink中的数据传输">3.2. Flink中的数据传输</h3>
<div class="paragraph">
<p>运行中的应用任务，会持续不断地交换数据。TaskManager负责将数据从“发送任务”（sending tasks）传递到“接收任务”（receiving tasks）。TaskManager的网络组件会在缓冲区中收集数据，然后再将其发送，也就是说，数据不是逐条发送的，而是在缓冲区中“攒”成了一批。这种技术是有效利用网络资源和实现高吞吐量的基础，机制类似于网络或磁盘I/O协议中使用的缓冲技术。</p>
</div>
<div class="admonitionblock note">
<table>
<tr>
<td class="icon">
<i class="fa icon-note" title="Note"></i>
</td>
<td class="content">
通过缓冲区来传递数据，意味着Flink的处理模型是基于微批的。
</td>
</tr>
</table>
</div>
<div class="paragraph">
<p>每个TaskManager都有一个网络缓冲池（默认大小为32KB），用于发送和接收数据。如果发送任务和接收任务运行在不同的TaskManager进程中，那么它们会通过操作系统的网络栈来进行通信。流应用程序需要以管道方式传递数据，所以每对TaskManager之间都需要维护一个永久TCP连接，用来交换数据。在无序连接模式下，每个发送任务都需要能向任何接收任务传递数据。所以我们发现，TaskManager需要为每一个接收任务设置一个专用的网络缓冲区，因为其中的每一个任务都需要接收数据。图3-4展示了这种架构。</p>
</div>
<div class="imageblock">
<div class="content">
<img src="images/spaf_0304.png" alt="spaf 0304">
</div>
</div>
<div class="paragraph">
<p>如图3-4所示，四个发送任务中的每一个都需要至少四个网络缓冲区，用来向每个接收任务发送数据，而每个接收任务也需要至少四个缓冲区来接收数据。需要发送到另一个TaskManager的缓冲数据，会复用同一网络连接。为了实现平滑的管道数据传输，TaskManager必须能够提供足够的缓冲，来同时为所有传出和传入连接提供服务。对于无序或广播连接，每个发送任务都需要为每个接收任务提供一个缓冲；所以，所需缓冲区的数量是相关算子任务数量的平方。Flink网络缓冲区的默认配置足以满足中小型应用；对于更大的应用场景，就需要按照“主内存和网络缓冲区”一节中的叙述调整配置了。</p>
</div>
<div class="paragraph">
<p>当发送任务和接收任务在同一个TaskManager进程中运行时，发送任务会将传出的数据序列化，放入字节缓冲区，并在缓冲区填满后将其放入队列。接收任务从队列中提取缓冲数据并对其进行反序列化。因此，在同一个TaskManager上运行的任务，它们之间的数据传输不会导致网络通信。</p>
</div>
<div class="paragraph">
<p>Flink采用不同的技术来降低任务之间的通信成本。在下面的部分中，我们会简要讨论基于信任度（Credit）的流控制和任务链。</p>
</div>
<div class="sect3">
<h4 id="_基于信任度credit的流控制">3.2.1. 基于信任度（credit）的流控制</h4>
<div class="paragraph">
<p>通过网络连接来发送每条数据的效率很低，会导致很大的开销。为了充分利用网络连接的带宽，就需要进行缓冲了。在流处理的上下文中，缓冲的一个缺点是会增加延迟，因为数据需要在缓冲区中进行收集，而不是立即发送。</p>
</div>
<div class="paragraph">
<p>Flink实现了一个基于信任度的流量控制机制，其工作原理如下。接收任务授予发送任务一些“信任度”（credit），也就是为了接收其数据而保留的网络缓冲区数。当发送者收到一个信任度通知，它就会按照被授予的信任度，发送尽可能多的缓冲数据，并且同时发送目前积压数据的大小——也就是已填满并准备发送的网络缓冲的数量。接收者用保留的缓冲区处理发来的数据，并对发送者传来的积压量进行综合考量，为其所有连接的发送者确定下一个信用度授权的优先级。</p>
</div>
<div class="paragraph">
<p>基于信用度的流控制可以减少延迟，因为发送者可以在接收者有足够的资源接受数据时立即发送数据。此外，在数据倾斜的情况下，这样分配网络资源是一种很有效的机制，因为信用度是根据发送者积压数据量的规模授予的。因此，基于信用的流量控制是Flink实现高吞吐量和低延迟的重要组成部分。</p>
</div>
</div>
<div class="sect3">
<h4 id="_任务链task_chaining">3.2.2. 任务链（Task Chaining）</h4>
<div class="paragraph">
<p>Flink采用了一种称为任务链的优化技术，可以在特定条件下减少本地通信的开销。为了满足任务链的要求，必须将两个或多个算子设为相同的并行度，并通过本地转发（local forward）的方式进行连接。图3-5所示的算子管道满足这些要求。它由三个算子组成，这些算子的任务并行度都被设为2，并且通过本地转发方式相连接。</p>
</div>
<div class="imageblock">
<div class="content">
<img src="images/spaf_0305.png" alt="spaf 0305">
</div>
</div>
<div class="paragraph">
<p>图3-6展示了管道以任务链方式运行的过程。算子的函数被融合成了一个单一的任务，由一个线程执行。由函数生成的数据通过一个简单的方法调用移交给下一个函数；这样在函数之间直接传递数据，基本上没有序列化和通信成本。</p>
</div>
<div class="imageblock">
<div class="content">
<img src="images/spaf_0306.png" alt="spaf 0306">
</div>
</div>
<div class="paragraph">
<p>任务链可以显著降低本地任务之间的通信成本，但也有一些场景，在没有链接的情况下运行管道操作是有意义的。例如，如果任务链中某个函数执行的开销巨大，那就可以将一条长的任务链管道断开，或者将一条链断开为两个任务，从而可以将这个开销大的函数调度到不同的槽（slots）中。图3-7显示了在没有任务链的情况下相同管道操作的执行情况。所有函数都由独立的单个任务来评估，每个任务都在专有的线程中运行。</p>
</div>
<div class="imageblock">
<div class="content">
<img src="images/spaf_0307.png" alt="spaf 0307">
</div>
</div>
<div class="paragraph">
<p>任务链在Flink中默认会启用。在“控制任务链”一节中，我们展示了如何禁用应用程序的任务链，以及如何控制各个算子的链接行为。</p>
</div>
</div>
</div>
<div class="sect2">
<h3 id="_事件时间event_time处理">3.3. 事件时间（Event-Time）处理</h3>
<div class="paragraph">
<p>在“时间语义”一节，我们重点强调了时间语义在流处理应用中的重要性，并且解释了处理时间（processing time）和事件时间（event time）的不同。处理时间比较好理解，因为它是基于处理器本地时间的；但同时，它会带来比较混乱、不一致、并且不可重现的结果。相比之下，事件时间语义能够产生可重现且一致的结果，这也是许多流处理场景希望解决的一大难题。但是，与处理时间应用程序相比，事件时间应用程序会更复杂，需要额外的配置。另外，支持事件时间的流处理器，也比纯粹在处理时间中运行的系统内部更为复杂。</p>
</div>
<div class="paragraph">
<p>Flink为常见的事件时间处理操作提供了直观且易于使用的原语，同时暴露了表达性很强的API，用户可以使用自定义算子实现更高级的事件时间应用程序。很好地理解Flink的内部时间处理，对于实现这样的高级应用程序会有很大帮助，有时也是必需的。上一章介绍了Flink利用两个概念来支持事件时间语义：记录时间戳（timestamps）和水位线（watermarks）。接下来，我们将描述Flink如何在内部实现并处理时间戳和水位线，进而支持具有事件时间语义的流式应用程序。</p>
</div>
<div class="sect3">
<h4 id="_时间戳timestamps">3.3.1. 时间戳（Timestamps）</h4>
<div class="paragraph">
<p>由Flink事件时间流应用程序处理的所有记录都必须伴有时间戳。时间戳将数据与特定时间点相关联，通常就是数据所表示的事件发生的时间点。而只要时间戳大致跟数据流保持一致，基本上随着数据流的前进而增大，应用程序就可以自由选择时间戳的含义。不过正如“时间语义”一节中所讨论的，在现实场景中，时间戳基本上都是乱序的，所以采用“事件时间”而非“处理事件”往往会显得更为重要。</p>
</div>
<div class="paragraph">
<p>当Flink以事件时间模式处理数据流时，它会根据数据记录的时间戳来处理基于时间的算子。例如，时间窗口算子根据相关时间戳将数据分配给不同的时间窗口。Flink将时间戳编码为16字节的长整型值，并将其作为元数据附加到数据记录中。它的内置运算符会将这个长整型值解释为一个具有毫秒精度的Unix时间戳，也就是1970-01-01-00:00:00.000以来的毫秒数。当然，如果用户进行了自定义，那么运算符可以有自己的解释，例如，可以将精度调整到微秒。</p>
</div>
</div>
<div class="sect3">
<h4 id="_水位线watermarks_2">3.3.2. 水位线(Watermarks)</h4>
<div class="paragraph">
<p>除了时间戳，基于事件时间的Flink应用程序还必须支持水位线（watermark）。在基于事件时间的应用中，水位线用于生成每个任务的当前事件时间。基于时间的算子使用这个“当前事件时间”来触发计算和处理操作。例如，一个时间窗口任务（time-window task）会在任务的事件时间超出窗口的关闭边界时，完成窗口计算，并输出计算结果。</p>
</div>
<div class="paragraph">
<p>在Flink中，水位线被实现为一条特殊的数据记录，它里面以长整型值保存了一个时间戳。水位线在带有时间戳的数据流中，跟随着其它数据一起流动，如图3-8所示。</p>
</div>
<div class="imageblock">
<div class="content">
<img src="images/spaf_0308.png" alt="spaf 0308">
</div>
</div>
<div class="paragraph">
<p>水位线有两个基本属性：</p>
</div>
<div class="ulist">
<ul>
<li>
<p>必须单调递增，以确保任务的事件时间时钟在向前推进，而不是在后退。</p>
</li>
<li>
<p>它们与数据的时间戳相关。带有时间戳T的水位线表示，所有后续数据的时间戳都应该大于T。</p>
</li>
</ul>
</div>
<div class="paragraph">
<p>上面的第二个属性用于处理带有乱序时间戳的数据流，比如图3-8中时间戳3和5的数据。基于时间的算子任务会收集和处理数据（这些数据可能具有乱序的时间戳），并在事件时间时钟到达某个时刻时完成计算。这个时刻就表示数据收集的截止，具有之前时间戳的数据应该都已经到达、不再需要了；而其中的事件时间时钟，正是由当前接收到的水位线来指示的。如果任务再接收到的数据违反了watermark的这一属性，也就是时间戳小于以前接收到的水位线时，它所属的那部分计算可能已经完成了。这种数据被称为延迟数据（late records）。Flink提供了处理延迟数据的不同方式，我们会在“处理延迟数据”一节中讨论。</p>
</div>
<div class="paragraph">
<p>水位线还有一个很有趣的特性，它允许应用程序自己来平衡结果的完整性和延迟。如果水位线与数据的时间戳非常接近，那么我们可以得到较低的处理延迟，因为任务在完成计算之前只会短暂地等待更多数据到达。而同时，结果的完整性可能会受到影响，因为相关数据可能因为迟到而被视为“延迟数据”，这样就不会包含在结果中。相反，非常保守的水位线提供了足够的时间去等待所有数据到达，这样会增加处理延迟，但提高了结果的完整性。</p>
</div>
</div>
<div class="sect3">
<h4 id="_watermark的传递和事件时间">3.3.3. watermark的传递和事件时间</h4>
<div class="paragraph">
<p>在本节中，我们将讨论算子如何处理水位线。Flink把watermark作为一条特殊的数据来实现，它也会由算子任务接收和发送。任务会有一个内部的时间服务，它会维护定时器，并在收到watermark时触发。任务可以在计时器服务中注册定时器，以便在将来特定的时间点执行计算。例如，窗口算子为每个活动窗口注册一个定时器，当事件时间超过窗口的结束时间时，该计时器将清除窗口的状态。</p>
</div>
<div class="paragraph">
<p>当任务收到watermark时，将执行以下操作：</p>
</div>
<div class="ulist">
<ul>
<li>
<p>任务根据watermark的时间戳更新其内部事件时钟。</p>
</li>
<li>
<p>任务的时间服务会将所有过期的计时器标识出来，它们的时间小于当前的事件时间。对于每个过期的计时器，任务调用一个回调函数，该函数可以执行计算并发送结果。</p>
</li>
<li>
<p>任务会发出一个带有更新后的事件时间的watermark。</p>
</li>
</ul>
</div>
<div class="admonitionblock note">
<table>
<tr>
<td class="icon">
<i class="fa icon-note" title="Note"></i>
</td>
<td class="content">
Flink限制通过DataStream API访问时间戳和watermark。函数不能读取或修改数据的时间戳和watermark，但底层的“处理函数”（process functions）除外，它们可以读取当前处理数据的时间戳、请求算子的当前事件时间，还可以注册定时器。通常的函数都不会暴露这些可以设置时间戳、操作任务事件时间时钟、或者发出水位线的API。而基于时间的数据流算子任务则会配置发送出的数据的时间戳，以确保它们能够与已到达的水位线平齐。例如，窗口计算完成后，时间窗口的算子任务会将窗口的结束时间作为时间戳附加到将要发送出的结果数据上，然后再使用触发窗口计算的时间戳发出watermark。
</td>
</tr>
</table>
</div>
<div class="paragraph">
<p>现在，让我们更详细地解释一下任务在接收到新的watermark时，如何继续发送watermark并更新其事件时钟。正如我们在“数据并发和任务并发”中所了解的，Flink将数据流拆分为多个分区，并通过单独的算子任务并行地处理每个分区。每个分区都是一个流，里面包含了带着时间戳的数据和watermark。一个算子与它前置或后续算子的连接方式有多种情况，所以它对应的任务可以从一个或多个“输入分区”接收数据和watermark，同时也可以将数据和watermark发送到一个或多个“输出分区”。接下来，我们将详细描述一个任务如何向多个输出任务发送watermark，以及如何通过接收到的watermark来驱动事件时间时钟前进。</p>
</div>
<div class="paragraph">
<p>任务为每个输入分区维护一个分区水位线（watermark）。当从一个分区接收到watermark时，它会比较新接收到的值和当前水位值，然后将相应的分区watermark更新为两者的最大值。然后，任务会比较所有分区watermark的大小，将其事件时钟更新为所有分区watermark的最小值。如果事件时间时钟前进了，任务就将处理所有被触发的定时器操作，并向所有连接的输出分区发送出相应的watermark，最终将新的事件时间广播给所有下游任务。</p>
</div>
<div class="paragraph">
<p>图3-9显示了具有四个输入分区和三个输出分区的任务如何接收watermark、更新分区watermark和事件时间时钟，以及向下游发出watermark。</p>
</div>
<div class="imageblock">
<div class="content">
<img src="images/spaf_0309.png" alt="spaf 0309">
</div>
</div>
<div class="paragraph">
<p>具有两个或多个输入流（如Union或CoFlatMap）的算子任务（参见“多流转换”一节）也会以所有分区watermark的最小值作为事件时间时钟。它们并不区分不同输入流的分区watermark，所以两个输入流的数据都是基于相同的事件时间时钟进行处理的。当然我们可以想到，如果应用程序的各个输入流的事件时间不一致，那么这种处理方式可能会导致问题。</p>
</div>
<div class="paragraph">
<p>Flink的水位处理和传递算法，确保了算子任务发出的时间戳和watermark是“对齐”的。不过它依赖一个条件，那就是所有分区都会提供不断增长的watermark。一旦一个分区不再推进水位线的上升，或者完全处于空闲状态、不再发送任何数据和watermark，任务的事件时间时钟就将停滞不前，任务的定时器也就无法触发了。对于基于时间的算子来说，它们需要依赖时钟的推进来执行计算和清除状态，这种情况显然就会有问题。如果任务没有定期从所有输入任务接收到新的watermark，那么基于时间的算子的处理延迟和状态空间的大小都会显著增加。</p>
</div>
<div class="paragraph">
<p>对于具有两个输入流而且watermark明显不同的算子，也会出现类似的情况。具有两个输入流的任务的事件时间时钟，将会同较慢的那条流的watermark保持一致，而通常较快流的数据或者中间结果会在state中缓冲，直到事件时间时钟达到这条流的watermark，才会允许处理它们。</p>
</div>
</div>
<div class="sect3">
<h4 id="_时间戳的分配和水位线的产生">3.3.4. 时间戳的分配和水位线的产生</h4>
<div class="paragraph">
<p>我们已经解释了什么是时间戳和水位线，以及它们是如何由Flink内部处理的；然而我们还没有讨论它们的产生。流应用程序接收到数据流时，通常就会先分配时间戳并生成水位线（watermark）。因为时间戳的选择是由不同的应用程序决定的，而且watermark取决于时间戳和流的特性，所以应用程序必须首先显式地分配时间戳并生成watermark。Flink流应用程序可以通过三种方式分配时间戳和生成watermark：</p>
</div>
<div class="ulist">
<ul>
<li>
<p>在数据源（source）处分配：当数据流被摄入到应用程序中时，可以由“源函数”SourceFunction分配和生成时间戳和watermark。SourceFunction可以产生并发送一个数据流；数据会与相关的时间戳一起发送出去，而watermark可以作为一条特殊数据在任何时间点发出。如果SourceFunction（暂时）不再发出watermark，它可以声明自己处于“空闲”（idle）状态。Flink会在后续算子的水位计算中，把空闲的SourceFunction产生的流分区排除掉。source的这一空闲机制，可以用来解决前面提到的水位不再上升的问题。源函数（Source Function）在“实现自定义源函数”一节中进行了更详细的讨论。</p>
</li>
<li>
<p>定期分配：在Flink中，DataStream API提供一个名为AssignerWithPeriodicWatermarks的用户定义函数，它可以从每个数据中提取时间戳，并被定期调用以生成当前watermark。提取出的时间戳被分配给相应的数据，而生成的watermark也会添加到流中。这个函数将在“分配时间戳和生成水位线”一节中讨论。</p>
</li>
<li>
<p>间断分配：AssignerWithPunctuatedWatermarks是另一个用户定义的函数，它同样会从每个数据中提取一个时间戳。它可以用于生成特殊输入数据中的watermark。与AssignerWithPeriodicWatermarks相比，此函数可以（但不是必须）从每个记录中提取watermark。我们在“分配时间戳和生成水位线”一节中同样讨论了该函数。</p>
</li>
</ul>
</div>
<div class="paragraph">
<p>用户定义的时间戳分配函数并没有严格的限制，通常会放在尽可能靠近source算子的位置，因为当经过一些算子处理后，数据及其时间戳的顺序就更加难以解释了。所以尽管我们可以在流应用程序的中段覆盖已有的时间戳和watermark——Flink通过用户定义的函数提供了这种灵活性，但这显然并不是推荐的做法。</p>
</div>
</div>
</div>
<div class="sect2">
<h3 id="_状态管理">3.4. 状态管理</h3>
<div class="paragraph">
<p>在第2章中，我们已经知道大多数流应用程序都是有状态的。许多算子会不断地读取和更新状态，例如在窗口中收集的数据、读取输入源的位置，或者像机器学习模型那样的用户定制化的算子状态。 Flink用同样的方式处理所有的状态，无论是内置的还是用户自定义的算子。本节我们将会讨论Flink支持的不同类型的状态，并解释“状态后端”是如何存储和维护状态的。</p>
</div>
<div class="paragraph">
<p>一般来说，由一个任务维护，并且用来计算某个结果的所有数据，都属于这个任务的状态。你可以认为状态就是一个本地变量，可以被任务的业务逻辑访问。图3-10显示了任务与其状态之间的交互。</p>
</div>
<div class="imageblock">
<div class="content">
<img src="images/spaf_0310.png" alt="spaf 0310">
</div>
</div>
<div class="paragraph">
<p>任务会接收一些输入数据。在处理数据时，任务可以读取和更新状态，并根据输入数据和状态计算结果。最简单的例子，就是统计接收到多少条数据的任务。当任务收到新数据时，它会访问状态以获取当前的计数，然后让计数递增，更新状态并发送出新的计数。</p>
</div>
<div class="paragraph">
<p>应用程序里，读取和写入状态的逻辑一般都很简单直接，而有效可靠的状态管理会复杂一些。这包括如何处理很大的状态——可能会超过内存，并且保证在发生故障时不会丢失任何状态。幸运的是，Flink会帮我们处理这相关的所有问题，包括状态一致性、故障处理以及高效存储和访问，以便开发人员可以专注于应用程序的逻辑。</p>
</div>
<div class="paragraph">
<p>在Flink中，状态始终与特定算子相关联。为了使运行时的Flink了解算子的状态，算子需要预先注册其状态。总的说来，有两种类型的状态：算子状态（operator state）和键控状态（keyed state），它们有着不同的范围访问，我们将在下面展开讨论。</p>
</div>
<div class="sect3">
<h4 id="_算子状态">3.4.1. 算子状态</h4>
<div class="paragraph">
<p>算子状态的作用范围限定为算子任务。这意味着由同一并行任务所处理的所有数据都可以访问到相同的状态，状态对于同一任务而言是共享的。算子状态不能由相同或不同算子的另一个任务访问。图3-11显示了任务如何访问算子状态。</p>
</div>
<div class="imageblock">
<div class="content">
<img src="images/spaf_0311.png" alt="spaf 0311">
</div>
</div>
<div class="paragraph">
<p>Flink为算子状态提供三种基本数据结构：</p>
</div>
<div class="sect4">
<h5 id="_列表状态list_state">列表状态（List state）</h5>
<div class="paragraph">
<p>将状态表示为一组数据的列表。</p>
</div>
</div>
<div class="sect4">
<h5 id="_联合列表状态union_list_state">联合列表状态（Union list state）</h5>
<div class="paragraph">
<p>也将状态表示为数据的列表。它与常规列表状态的区别在于，在发生故障时，或者从保存点（savepoint）启动应用程序时如何恢复。我们将在后面继续讨论。</p>
</div>
</div>
<div class="sect4">
<h5 id="_广播状态broadcast_state">广播状态（Broadcast state）</h5>
<div class="paragraph">
<p>如果一个算子有多项任务，而它的每项任务状态又都相同，那么这种特殊情况最适合应用广播状态。在保存检查点和重新调整算子并行度时，会用到这个特性。这两部分内容将在本章后面讨论。</p>
</div>
</div>
</div>
<div class="sect3">
<h4 id="_键控状态keyed_state">3.4.2. 键控状态（Keyed State）</h4>
<div class="paragraph">
<p>顾名思义，键控状态是根据输入数据流中定义的键（key）来维护和访问的。Flink为每个键值维护一个状态实例，并将具有相同键的所有数据，都分区到同一个算子任务中，这个任务会维护和处理这个key对应的状态。当任务处理一条数据时，它会自动将状态的访问范围限定为当前数据的key。因此，具有相同key的所有数据都会访问相同的状态。图3-12显示了任务如何与键控状态进行交互。</p>
</div>
<div class="imageblock">
<div class="content">
<img src="images/spaf_0312.png" alt="spaf 0312">
</div>
</div>
<div class="paragraph">
<p>我们可以将键控状态看成是在算子所有并行任务上，对键进行分区（或分片）之后的一个键值映射（key-value map）。 Flink为键控状态提供不同的数据结构，用于确定map中每个key存储的值的类型。我们简单了解一下最常见的键控状态。</p>
</div>
<div class="sect4">
<h5 id="_值状态value_state">值状态（Value state）</h5>
<div class="paragraph">
<p>为每个键存储一个任意类型的单个值。复杂数据结构也可以存储为值状态。</p>
</div>
</div>
<div class="sect4">
<h5 id="_列表状态list_state_2">列表状态（List state）</h5>
<div class="paragraph">
<p>为每个键存储一个值的列表。列表里的每个数据可以是任意类型。</p>
</div>
</div>
<div class="sect4">
<h5 id="_映射状态map_state">映射状态（Map state）</h5>
<div class="paragraph">
<p>为每个键存储一个键值映射（map）。map的key和value可以是任意类型。</p>
</div>
<div class="paragraph">
<p>状态的数据结构可以让Flink实现更有效的状态访问。我们将在“在运行时上下文（RuntimeContext）中声明键控状态”中做进一步讨论。</p>
</div>
</div>
</div>
<div class="sect3">
<h4 id="_状态后端state_backends">3.4.3. 状态后端（State Backends）</h4>
<div class="paragraph">
<p>每传入一条数据，有状态的算子任务都会读取和更新状态。由于有效的状态访问对于处理数据的低延迟至关重要，因此每个并行任务都会在本地维护其状态，以确保快速的状态访问。状态到底是如何被存储、访问以及维护的？这件事由一个可插入的组件决定，这个组件就叫做状态后端（state backend）。状态后端主要负责两件事：本地的状态管理，以及将检查点（checkpoint）状态写入远程存储。</p>
</div>
<div class="paragraph">
<p>对于本地状态管理，状态后端会存储所有键控状态，并确保所有的访问都被正确地限定在当前键范围。 Flink提供了默认的状态后端，会将键控状态作为内存中的对象进行管理，将它们存储在JVM堆上。另一种状态后端则会把状态对象进行序列化，并将它们放入RocksDB中，然后写入本地硬盘。第一种方式可以提供非常快速的状态访问，但它受内存大小的限制；而访问RocksDB状态后端存储的状态速度会较慢，但其状态可以增长到非常大。</p>
</div>
<div class="paragraph">
<p>状态检查点的写入也非常重要，这是因为Flink是一个分布式系统，而状态只能在本地维护。 TaskManager进程（所有任务在其上运行）可能在任何时间点挂掉。因此，它的本地存储只能被认为是不稳定的。状态后端负责将任务的状态检查点写入远程的持久存储。写入检查点的远程存储可以是分布式文件系统，也可以是数据库。不同的状态后端在状态检查点的写入机制方面有所不同。例如，RocksDB状态后端支持增量的检查点，这对于非常大的状态来说，可以显著减少状态检查点写入的开销。</p>
</div>
<div class="paragraph">
<p>我们将在“选择状态后端”一节中更详细地讨论不同的状态后端及其优缺点。</p>
</div>
</div>
<div class="sect3">
<h4 id="_调整有状态算子的并行度">3.4.4. 调整有状态算子的并行度</h4>
<div class="paragraph">
<p>流应用程序的一个常见要求是，为了增大或较小输入数据的速率，需要灵活地调整算子的并行度。对于无状态算子而言，并行度的调整没有任何问题，但更改有状态算子的并行度显然就没那么简单了，因为它们的状态需要重新分区并分配给更多或更少的并行任务。 Flink支持四种模式来调整不同类型的状态。</p>
</div>
<div class="paragraph">
<p>具有键控状态的算子通过将键重新分区为更少或更多任务来缩放并行度。不过，并行度调整时任务之间会有一些必要的状态转移。为了提高效率，Flink并不会对单独的key做重新分配，而是用所谓的“键组”（key group）把键管理起来。键组是key的分区形式，同时也是Flink为任务分配key的方式。图3-13显示了如何在键组中重新分配键控状态。</p>
</div>
<div class="imageblock">
<div class="content">
<img src="images/spaf_0313.png" alt="spaf 0313">
</div>
</div>
<div class="paragraph">
<p>具有算子列表状态的算子，会通过重新分配列表中的数据项目来进行并行度缩放。从概念上讲，所有并行算子任务的列表项目会被收集起来，并将其均匀地重新分配给更少或更多的任务。如果列表条目少于算子的新并行度，则某些任务将以空状态开始。图3-14显示了算子列表状态的重新分配。</p>
</div>
<div class="imageblock">
<div class="content">
<img src="images/spaf_0314.png" alt="spaf 0314">
</div>
</div>
<div class="paragraph">
<p>具有算子联合列表状态的算子，会通过向每个任务广播状态的完整列表，来进行并行度的缩放。然后，任务可以选择要使用的状态项和要丢弃的状态项。图3-15显示了如何重新分配算子联合列表状态。</p>
</div>
<div class="imageblock">
<div class="content">
<img src="images/spaf_0315.png" alt="spaf 0315">
</div>
</div>
<div class="paragraph">
<p>具有算子广播状态的算子，通过将状态复制到新任务，来增大任务的并行度。这是没问题的，因为广播状态保证了所有任务都具有相同的状态。而对于缩小并行度的情况，我们可以直接取消剩余任务，因为状态是相同的，已经被复制并且不会丢失。图3-16显示了算子广播状态的重新分配。</p>
</div>
<div class="imageblock">
<div class="content">
<img src="images/spaf_0316.png" alt="spaf 0316">
</div>
</div>
</div>
</div>
<div class="sect2">
<h3 id="_检查点保存点和状态恢复">3.5. 检查点，保存点和状态恢复</h3>
<div class="paragraph">
<p>Flink是一个分布式数据处理系统，因此必须有一套机制处理各种故障，比如被杀掉的进程，故障的机器和中断的网络连接。任务都是在本地维护状态的，所以Flink必须确保状态不会丢失，并且在发生故障时能够保持一致。</p>
</div>
<div class="paragraph">
<p>在本节中，我们将介绍Flink的检查点（checkpoint）和恢复机制，这保证了“精确一次”（exactly-once）的状态一致性。我们还会讨论Flink独特的保存点（savepoint）功能，这是一个“瑞士军刀”式的工具，可以解决许多操作数据流时面对的问题。</p>
</div>
<div class="sect3">
<h4 id="_一致的检查点checkpoints">3.5.1. 一致的检查点（Checkpoints）</h4>
<div class="paragraph">
<p>Flink的恢复机制的核心，就是应用状态的一致检查点。有状态流应用的一致检查点，其实就是所有任务状态在某个时间点的一份拷贝，而这个时间点应该是所有任务都恰好处理完一个相同的输入数据的时候。这个过程可以通过一致检查点的一个简单算法步骤来解释。这个算法的步骤是：</p>
</div>
<div class="ulist">
<ul>
<li>
<p>暂停所有输入流的摄取，也就是不再接收新数据的输入。</p>
</li>
<li>
<p>等待所有正在处理的数据计算完毕，这意味着结束时，所有任务都已经处理了所有输入数据。</p>
</li>
<li>
<p>通过将每个任务的状态复制到远程持久存储，来得到一个检查点。所有任务完成拷贝操作后，检查点就完成了。</p>
</li>
<li>
<p>恢复所有输入流的摄取。</p>
</li>
</ul>
</div>
<div class="paragraph">
<p>需要注意，Flink实现的并不是这种简单的机制。我们将在本节后面介绍Flink更精妙的检查点算法。</p>
</div>
<div class="paragraph">
<p>图3-17显示了一个简单应用中的一致检查点。</p>
</div>
<div class="imageblock">
<div class="content">
<img src="images/spaf_0317.png" alt="spaf 0317">
</div>
</div>
<div class="paragraph">
<p>上面的应用程序中具有单一的输入源（source）任务，输入数据就是一组不断增长的数字的流——1,2,3等。数字流被划分为偶数流和奇数流。求和算子（sum）的两个任务会分别实时计算当前所有偶数和奇数的总和。源任务会将其输入流的当前偏移量存储为状态，而求和任务则将当前的总和值存储为状态。在图3-17中，Flink在输入偏移量为5时，将检查点写入了远程存储，当前的总和为6和9。</p>
</div>
</div>
<div class="sect3">
<h4 id="_从一致检查点中恢复状态">3.5.2. 从一致检查点中恢复状态</h4>
<div class="paragraph">
<p>在执行流应用程序期间，Flink会定期检查状态的一致检查点。如果发生故障，Flink将会使用最近的检查点来一致恢复应用程序的状态，并重新启动处理流程。图3-18显示了恢复过程。</p>
</div>
<div class="imageblock">
<div class="content">
<img src="images/spaf_0318.png" alt="spaf 0318">
</div>
</div>
<div class="paragraph">
<p>应用程序从检查点的恢复分为三步：</p>
</div>
<div class="ulist">
<ul>
<li>
<p>重新启动整个应用程序。</p>
</li>
<li>
<p>将所有的有状态任务的状态重置为最近一次的检查点。</p>
</li>
<li>
<p>恢复所有任务的处理。</p>
</li>
</ul>
</div>
<div class="paragraph">
<p>这种检查点的保存和恢复机制可以为应用程序状态提供“精确一次”（exactly-once）的一致性，因为所有算子都会保存检查点并恢复其所有状态，这样一来所有的输入流就都会被重置到检查点完成时的位置。至于数据源是否可以重置它的输入流，这取决于其实现方式和消费流数据的外部接口。例如，像Apache Kafka这样的事件日志系统可以提供流上之前偏移位置的数据，所以我们可以将源重置到之前的偏移量，重新消费数据。而从套接字（socket）消费数据的流就不能被重置了，因为套接字的数据一旦被消费就会丢弃掉。因此，对于应用程序而言，只有当所有的输入流消费的都是可重置的数据源时，才能确保在“精确一次”的状态一致性下运行。</p>
</div>
<div class="paragraph">
<p>从检查点重新启动应用程序后，其内部状态与检查点完成时的状态完全相同。然后它就会开始消费并处理检查点和发生故障之间的所有数据。尽管这意味着Flink会对一些数据处理两次（在故障之前和之后），我们仍然可以说这个机制实现了精确一次的一致性语义，因为所有算子的状态都已被重置，而重置后的状态下还不曾看到这些数据。</p>
</div>
<div class="paragraph">
<p>我们必须指出，Flink的检查点保存和恢复机制仅仅可以重置流应用程序的内部状态。对于应用中的一些的输出（sink）算子，在恢复期间，某些结果数据可能会多次发送到下游系统，比如事件日志、文件系统或数据库。对于某些存储系统，Flink提供了具有精确一次输出功​​能的sink函数，比如，可以在检查点完成时提交发出的记录。另一种适用于许多存储系统的方法是幂等更新。在“应用程序一致性保证”一节中，我们还会详细讨论如何解决应用程序端到端的精确一次一致性问题。</p>
</div>
</div>
<div class="sect3">
<h4 id="_flink的检查点算法">3.5.3. Flink的检查点算法</h4>
<div class="paragraph">
<p>Flink的恢复机制，基于它的一致性检查点。前面我们已经了解了从流应用中创建检查点的简单方法——先暂停应用，保存检查点，然后再恢复应用程序，这种方法很好理解，但它的理念是“停止一切”，这对于即使是中等延迟要求的应用程序而言也是不实用的。所以Flink没有这么简单粗暴，而是基于Chandy-Lamport算法实现了分布式快照的检查点保存。该算法并不会暂停整个应用程序，而是将检查点的保存与数据处理分离，这样就可以实现在其它任务做检查点状态保存状态时，让某些任务继续进行而不受影响。接下来我们将解释此算法的工作原理。</p>
</div>
<div class="paragraph">
<p>Flink的检查点算法用到了一种称为“检查点分界线”（checkpoint barrier）的特殊数据形式。与水位线（watermark）类似，检查点分界线由source算子注入到常规的数据流中，它的位置是限定好的，不能超过其他数据，也不能被后面的数据超过。检查点分界线带有检查点ID，用来标识它所属的检查点；这样，这个分界线就将一条流逻辑上分成了两部分。分界线之前到来的数据导致的状态更改，都会被包含在当前分界线所属的检查点中；而基于分界线之后的数据导致的所有更改，就会被包含在之后的检查点中。</p>
</div>
<div class="paragraph">
<p>我们用一个简单的流应用程序作为示例，来一步一步解释这个算法。该应用程序有两个源（source）任务，每个任务都消费一个增长的数字流。源任务的输出被划分为两部分：偶数和奇数的流。每个分区由一个任务处理，该任务计算所有收到的数字的总和，并将更新的总和转发给输出（sink）任务。这个应用程序的结构如图3-19所示。</p>
</div>
<div class="imageblock">
<div class="content">
<img src="images/spaf_0319.png" alt="spaf 0319">
</div>
</div>
<div class="paragraph">
<p>JobManager会向每个数据源（source）任务发送一条带有新检查点ID的消息，通过这种方式来启动检查点，如图3-20所示。</p>
</div>
<div class="imageblock">
<div class="content">
<img src="images/spaf_0320.png" alt="spaf 0320">
</div>
</div>
<div class="paragraph">
<p>当source任务收到消息时，它会暂停发出新的数据，在状态后端触发本地状态的检查点保存，并向所有传出的流分区广播带着检查点ID的分界线（barriers）。状态后端在状态检查点完成后会通知任务，而任务会向JobManager确认检查点完成。在发出所有分界线后，source任务就可以继续常规操作，发出新的数据了。通过将分界线注入到输出流中，源函数（source function）定义了检查点在流中所处的位置。图3-21显示了两个源任务将本地状态保存到检查点，并发出检查点分界线之后的流应用程序。</p>
</div>
<div class="imageblock">
<div class="content">
<img src="images/spaf_0321.png" alt="spaf 0321">
</div>
</div>
<div class="paragraph">
<p>源任务发出的检查点分界线（barrier），将被传递给所连接的任务。与水位线（watermark）类似，barrier会被广播到所有连接的并行任务，以确保每个任务从它的每个输入流中都能接收到。当任务收到一个新检查点的barrier时，它会等待这个检查点的所有输入分区的barrier到达。在等待的过程中，任务并不会闲着，而是会继续处理尚未提供barrier的流分区中的数据。对于那些barrier已经到达的分区，如果继续有新的数据到达，它们就不会被立即处理，而是先缓存起来。这个等待所有分界线到达的过程，称为“分界线对齐”（barrier alignment），如图3-22所示。</p>
</div>
<div class="imageblock">
<div class="content">
<img src="images/spaf_0322.png" alt="spaf 0322">
</div>
</div>
<div class="paragraph">
<p>当任务从所有输入分区都收到barrier时，它就会在状态后端启动一个检查点的保存，并继续向所有下游连接的任务广播检查点分界线，如图3-23所示。</p>
</div>
<div class="imageblock">
<div class="content">
<img src="images/spaf_0323.png" alt="spaf 0323">
</div>
</div>
<div class="paragraph">
<p>所有的检查点barrier都发出后，任务就开始处理之前缓冲的数据。在处理并发出所有缓冲数据之后，任务就可以继续正常处理输入流了。图3-24显示了此时的应用程序。</p>
</div>
<div class="imageblock">
<div class="content">
<img src="images/spaf_0324.png" alt="spaf 0324">
</div>
</div>
<div class="paragraph">
<p>最终，检查点分界线会到达输出（sink）任务。当sink任务接收到barrier时，它也会先执行“分界线对齐”，然后将自己的状态保存到检查点，并向JobManager确认已接收到barrier。一旦从应用程序的所有任务收到一个检查点的确认信息，JobManager就会将这个检查点记录为已完成。图3-25显示了检查点算法的最后一步。这样，当发生故障时，我们就可以用已完成的检查点恢复应用程序了。</p>
</div>
<div class="imageblock">
<div class="content">
<img src="images/spaf_0325.png" alt="spaf 0325">
</div>
</div>
</div>
<div class="sect3">
<h4 id="_检查点的性能影响">3.5.4. 检查点的性能影响</h4>
<div class="paragraph">
<p>Flink的检查点算法可以在不停止整个应用程序的情况下，生成一致的分布式检查点。但是，它可能会增加应用程序的处理延迟。Flink对此有一些调整措施，可以在某些场景下显得对性能的影响没那么大。</p>
</div>
<div class="paragraph">
<p>当任务将其状态保存到检查点时，它其实处于一个阻塞状态，而此时新的输入会被缓存起来。由于状态可能变得非常大，而且检查点需要通过网络将数据写入远程存储系统，检查点的写入很容易就会花费几秒到几分钟的时间——这对于要求低延迟的应用程序而言，显然是不可接受的。在Flink的设计中，真正负责执行检查点写入的，其实是状态后端。具体怎样复制任务的状态，取决于状态后端的实现方式。例如，文件系统（FileSystem）状态后端和RocksDB状态后端都支持了异步（asynchronous）检查点。触发检查点操作时，状态后端会先创建状态的本地副本。本地拷贝完成后，任务就将继续常规的数据处理，这往往并不会花费太多时间。一个后台线程会将本地快照异步复制到远程存储，并在完成检查点后再回来通知任务。异步检查点的机制，显著减少了任务继续处理数据之前的等待时间。此外，RocksDB状态后端还实现了增量的检查点，这样可以大大减少要传输的数据量。</p>
</div>
<div class="paragraph">
<p>为了减少检查点算法对处理延迟的影响，另一种技术是调整分界线对齐的步骤。对于需要非常低的延迟、并且可以容忍“至少一次”（at-least-once）状态保证的应用程序，Flink可以将检查点算法配置为，在等待barrier对齐期间处理所有到达的数据，而不是把barrier已经到达的那些分区的数据缓存起来。当检查点的所有barrier到达，算子任务就会将状态写入检查点——当然，现在的状态中，就可能包括了一些“提前”的更改，这些更改由本该属于下一个检查点的数据到来时触发。如果发生故障，从检查点恢复时，就将再次处理这些数据：这意味着检查点现在提供的是“至少一次”（at-least-once）而不是“精确一次”（exactly-once）的一致性保证。</p>
</div>
</div>
<div class="sect3">
<h4 id="_保存点savepoints">3.5.5. 保存点（Savepoints）</h4>
<div class="paragraph">
<p>Flink的恢复算法是基于状态检查点的。Flink根据可配置的策略，定期保存并自动丢弃检查点。检查点的目的是确保在发生故障时可以重新启动应用程序，所以当应用程序被显式地撤销（cancel）时，检查点会被删除掉。除此之外，应用程序状态的一致性快照还可用于除故障恢复之外的更多功能。</p>
</div>
<div class="paragraph">
<p>Flink中一个最有价值，也是最独特的功能是保存点（savepoints）。原则上，创建保存点使用的算法与检查点完全相同，因此保存点可以认为就是具有一些额外元数据的检查点。 Flink不会自动创建保存点，因此用户（或者外部调度程序）必须明确地触发创建操作。同样，Flink也不会自动清理保存点。第10章将会具体介绍如何触发和处理保存点。</p>
</div>
<div class="sect4">
<h5 id="_使用保存点">使用保存点</h5>
<div class="paragraph">
<p>有了应用程序和与之兼容的保存点，我们就可以从保存点启动应用程序了。这会将应用程序的状态初始化为保存点的状态，并从保存点创建时的状态开始运行应用程序。虽然看起来这种行为似乎与用检查点从故障中恢复应用程序完全相同，但实际上故障恢复只是一种特殊情况，它只是在相同的集群上以相同的配置启动相同的应用程序。而从保存点启动应用程序会更加灵活，这就可以让我们做更多事情了。</p>
</div>
<div class="ulist">
<ul>
<li>
<p>可以从保存点启动不同但兼容的应用程序。这样一来，我们就可以及时修复应用程序中的逻辑bug，并让流式应用的源尽可能多地提供之前发生的事件，然后重新处理，以便修复之前的计算结果。修改后的应用程序还可用于运行A / B测试，或者具有不同业务逻辑的假设场景。这里要注意，应用程序和保存点必须兼容才可以这么做——也就是说，应用程序必须能够加载保存点的状态。</p>
</li>
<li>
<p>可以使用不同的并行度来启动相同的应用程序，可以将应用程序的并行度增大或减小。</p>
</li>
<li>
<p>可以在不同的集群上启动同样的应用程序。这非常有意义，意味着我们可以将应用程序迁移到较新的Flink版本或不同的集群上去。</p>
</li>
<li>
<p>可以使用保存点暂停应用程序，稍后再恢复。这样做的意义在于，可以为更高优先级的应用程序释放集群资源，或者在输入数据不连续生成时释放集群资源。</p>
</li>
<li>
<p>还可以将保存点设置为某一版本，并归档（archive）存储应用程序的状态。</p>
</li>
</ul>
</div>
<div class="paragraph">
<p>保存点是非常强大的功能，所以许多用户会定期创建保存点以便能够及时退回之前的状态。我们见到的各种场景中，保存点一个最有趣的应用是不断将流应用程序迁移到更便宜的数据中心上去。</p>
</div>
</div>
<div class="sect4">
<h5 id="_从保存点启动应用程序">从保存点启动应用程序</h5>
<div class="paragraph">
<p>前面提到的保存点的所有用例，都遵循相同的模式。那就是首先创建正在运行的应用程序的保存点，然后在一个新启动的应用程序中用它来恢复状态。之前我们已经知道，保存点的创建和检查点非常相似，而接下来我们就将介绍对于一个从保存点启动的应用程序，Flink如何初始化其状态。</p>
</div>
<div class="paragraph">
<p>应用程序由多个算子组成。每个算子可以定义一个或多个键控状态和算子状态。算子由一个或多个算子任务并行执行。因此，一个典型的应用程序会包含多个状态，这些状态分布在多个算子任务中，这些任务可以运行在不同的TaskManager进程上。</p>
</div>
<div class="paragraph">
<p>图3-26显示了一个具有三个算子的应用程序，每个算子执行两个算子任务。一个算子（OP-1）具有单一的算子状态（OS-1），而另一个算子（OP-2）具有两个键控状态（KS-1和KS-2）。当保存点创建时，会将所有任务的状态复制到持久化的存储位置。</p>
</div>
<div class="paragraph">
<p>保存点中的状态拷贝会以算子标识符（operator ID）和状态名称（state name）组织起来。算子ID和状态名称必须能够将保存点的状态数据，映射到一个正在启动的应用程序的算子状态。从保存点启动应用程序时，Flink会将保存点的数据重新分配给相应的算子任务。</p>
</div>
<div class="admonitionblock note">
<table>
<tr>
<td class="icon">
<i class="fa icon-note" title="Note"></i>
</td>
<td class="content">
请注意，保存点不包含有关算子任务的信息。这是因为当应用程序以不同的并行度启动时，任务数量可能会更改。
</td>
</tr>
</table>
</div>
<div class="paragraph">
<p>如果我们要从保存点启动一个修改过的应用程序，那么保存点中的状态只能映射到符合标准的应用程序——它里面的算子必须具有相应的ID和状态名称。默认情况下，Flink会自动分配唯一的算子ID。然而，一个算子的ID，是基于它之前算子的ID确定性地生成的。因此，算子的ID会在其前序算子改变时改变，比如，当我们添加了新的或移除掉一个算子时，前序算子ID改变，当前算子ID就会变化。所以对于具有默认算子ID的应用程序而言，如果想在不丢失状态的前提下升级，就会受到极大的限制。因此，我们强烈建议在程序中为算子手动分配唯一ID，而不是依靠Flink的默认分配。我们将在“指定唯一的算子标识符”一节中详细说明如何分配算子标识符。</p>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="sect1">
<h2 id="_编写第一个flink程序">4. 编写第一个Flink程序</h2>
<div class="sectionbody">
<div class="sect2">
<h3 id="_在idea中编写flink程序">4.1. 在IDEA中编写Flink程序</h3>
<div class="paragraph">
<p>本项目使用的Flink版本为最新版本，也就是1.10.0。现在提供maven项目的配置文件。</p>
</div>
<div class="olist arabic">
<ol class="arabic">
<li>
<p>使用Intellij IDEA创建一个Maven新项目</p>
</li>
<li>
<p>勾选<code>Create from archetype</code>，然后点击<code>Add Archetype</code>按钮</p>
</li>
<li>
<p><code>GroupId</code>中输入<code>org.apache.flink</code>，<code>ArtifactId</code>中输入<code>flink-quickstart-scala</code>，<code>Version</code>中输入<code>1.10.0</code>，然后点击<code>OK</code></p>
</li>
<li>
<p>点击向右箭头，出现下拉列表，选中<code>flink-quickstart-scala:1.10.0</code>，点击<code>Next</code></p>
</li>
<li>
<p><code>Name</code>中输入<code>FlinkTutorial</code>，<code>GroupId</code>中输入<code>com.atguigu</code>，<code>ArtifactId</code>中输入<code>FlinkTutorial</code>，点击<code>Next</code></p>
</li>
<li>
<p>最好使用IDEA默认的Maven工具：Bundled（Maven 3），点击<code>Finish</code>，等待一会儿，项目就创建好了</p>
</li>
</ol>
</div>
<div class="paragraph">
<p>编写<code>WordCount.scala</code>程序</p>
</div>
<div class="listingblock">
<div class="title">WordCount.scala</div>
<div class="content">
<pre class="pygments highlight"><code data-lang="scala"><span></span><span class="tok-k">package</span> <span class="tok-nn">com.atguigu</span>

<span class="tok-k">import</span> <span class="tok-nn">org.apache.flink.streaming.api.scala._</span> <i class="conum" data-value="1"></i><b>(1)</b>
<span class="tok-k">import</span> <span class="tok-nn">org.apache.flink.streaming.api.windowing.time.Time</span>

<span class="tok-k">object</span> <span class="tok-nc">StreamingJob</span> <span class="tok-o">{</span>

  <span class="tok-cm">/** Main program method */</span>
  <span class="tok-k">def</span> <span class="tok-n">main</span><span class="tok-o">(</span><span class="tok-n">args</span><span class="tok-k">:</span> <span class="tok-kt">Array</span><span class="tok-o">[</span><span class="tok-kt">String</span><span class="tok-o">])</span> <span class="tok-k">:</span> <span class="tok-kt">Unit</span> <span class="tok-o">=</span> <span class="tok-o">{</span>

    <span class="tok-c1">// get the execution environment</span>
    <span class="tok-k">val</span> <span class="tok-n">env</span><span class="tok-k">:</span> <span class="tok-kt">StreamExecutionEnvironment</span> <span class="tok-o">=</span> <span class="tok-nc">StreamExecutionEnvironment</span><span class="tok-o">.</span><span class="tok-n">getExecutionEnvironment</span>

    <span class="tok-c1">// get input data by connecting to the socket</span>
    <span class="tok-k">val</span> <span class="tok-n">text</span><span class="tok-k">:</span> <span class="tok-kt">DataStream</span><span class="tok-o">[</span><span class="tok-kt">String</span><span class="tok-o">]</span> <span class="tok-k">=</span> <span class="tok-n">env</span><span class="tok-o">.</span><span class="tok-n">socketTextStream</span><span class="tok-o">(</span><span class="tok-s">&quot;localhost&quot;</span><span class="tok-o">,</span> <span class="tok-mi">9999</span><span class="tok-o">,</span> <span class="tok-sc">&#39;\n&#39;</span><span class="tok-o">)</span>

    <span class="tok-c1">// parse the data, group it, window it, and aggregate the counts</span>
    <span class="tok-k">val</span> <span class="tok-n">windowCounts</span> <span class="tok-k">=</span> <span class="tok-n">text</span>
      <span class="tok-o">.</span><span class="tok-n">flatMap</span> <span class="tok-o">{</span> <span class="tok-n">w</span> <span class="tok-k">=&gt;</span> <span class="tok-n">w</span><span class="tok-o">.</span><span class="tok-n">split</span><span class="tok-o">(</span><span class="tok-s">&quot;\\s&quot;</span><span class="tok-o">)</span> <span class="tok-o">}</span>
      <span class="tok-o">.</span><span class="tok-n">map</span> <span class="tok-o">{</span> <span class="tok-n">w</span> <span class="tok-k">=&gt;</span> <span class="tok-nc">WordWithCount</span><span class="tok-o">(</span><span class="tok-n">w</span><span class="tok-o">,</span> <span class="tok-mi">1</span><span class="tok-o">)</span> <span class="tok-o">}</span>
      <span class="tok-o">.</span><span class="tok-n">keyBy</span><span class="tok-o">(</span><span class="tok-s">&quot;word&quot;</span><span class="tok-o">)</span>
      <span class="tok-o">.</span><span class="tok-n">timeWindow</span><span class="tok-o">(</span><span class="tok-nc">Time</span><span class="tok-o">.</span><span class="tok-n">seconds</span><span class="tok-o">(</span><span class="tok-mi">5</span><span class="tok-o">))</span>
      <span class="tok-o">.</span><span class="tok-n">sum</span><span class="tok-o">(</span><span class="tok-s">&quot;count&quot;</span><span class="tok-o">)</span>

    <span class="tok-c1">// print the results with a single thread, rather than in parallel</span>
    <span class="tok-n">windowCounts</span><span class="tok-o">.</span><span class="tok-n">print</span><span class="tok-o">().</span><span class="tok-n">setParallelism</span><span class="tok-o">(</span><span class="tok-mi">1</span><span class="tok-o">)</span>

    <span class="tok-n">env</span><span class="tok-o">.</span><span class="tok-n">execute</span><span class="tok-o">(</span><span class="tok-s">&quot;Socket Window WordCount&quot;</span><span class="tok-o">)</span>
  <span class="tok-o">}</span>

  <span class="tok-cm">/** Data type for words with count */</span>
  <span class="tok-k">case</span> <span class="tok-k">class</span> <span class="tok-nc">WordWithCount</span><span class="tok-o">(</span><span class="tok-n">word</span><span class="tok-k">:</span> <span class="tok-kt">String</span><span class="tok-o">,</span> <span class="tok-n">count</span><span class="tok-k">:</span> <span class="tok-kt">Long</span><span class="tok-o">)</span>
<span class="tok-o">}</span></code></pre>
</div>
</div>
<div class="colist arabic">
<table>
<tr>
<td><i class="conum" data-value="1"></i><b>1</b></td>
<td>这一行必须导入，看清楚了别导错了，因为要把一些隐式类型转换导进来。</td>
</tr>
</table>
</div>
<div class="paragraph">
<p>打开一个终端（Terminal），运行以下命令</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="pygments highlight"><code data-lang="shell"><span></span>nc -lk <span class="tok-m">9999</span></code></pre>
</div>
</div>
<div class="paragraph">
<p>接下来使用<code>IDEA</code>运行就可以了。</p>
</div>
</div>
<div class="sect2">
<h3 id="_下载flink运行时环境提交jar包的运行方式">4.2. 下载Flink运行时环境，提交Jar包的运行方式</h3>
<div class="paragraph">
<p>下载链接：http://mirror.bit.edu.cn/apache/flink/flink-1.10.0/flink-1.10.0-bin-scala_2.11.tgz</p>
</div>
<div class="paragraph">
<p>然后解压</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="pygments highlight"><code data-lang="shell"><span></span>tar xvfz flink-1.10.0-bin-scala_2.11.tgz</code></pre>
</div>
</div>
<div class="paragraph">
<p>启动Flink集群</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="pygments highlight"><code data-lang="shell"><span></span><span class="tok-nb">cd</span> flink-1.10.0
./bin/start-cluster.sh</code></pre>
</div>
</div>
<div class="paragraph">
<p>可以打开Flink WebUI查看集群状态：http://localhost:8081</p>
</div>
<div class="paragraph">
<p>在<code>IDEA</code>中使用<code>maven package</code>打包。</p>
</div>
<div class="paragraph">
<p>提交打包好的<code>JAR</code>包</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="pygments highlight"><code data-lang="shell"><span></span><span class="tok-nb">cd</span> flink-1.10.0
./bin/flink run 打包好的JAR包的绝对路径</code></pre>
</div>
</div>
<div class="paragraph">
<p>停止Flink集群</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="pygments highlight"><code data-lang="shell"><span></span>./bin/stop-cluster.sh</code></pre>
</div>
</div>
<div class="paragraph">
<p>查看标准输出日志的位置，在<code>log</code>文件夹中。</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="pygments highlight"><code data-lang="shell"><span></span><span class="tok-nb">cd</span> flink-1.10.0/log</code></pre>
</div>
</div>
</div>
</div>
</div>
<div class="sect1">
<h2 id="_flink_datastream_api">5. Flink DataStream API</h2>
<div class="sectionbody">
<div class="paragraph">
<p>本章介绍了Flink DataStream API的基本知识。我们展示了典型的Flink流处理程序的结构和组成部分，还讨论了Flink的类型系统以及支持的数据类型，还展示了数据和分区转换操作。窗口操作符，基于时间语义的转换操作，有状态的操作符，以及和外部系统的连接器将在接下来的章节进行介绍。阅读完这一章后，我们将会知道如何去实现一个具有基本功能的流处理程序。我们的示例程序采用Scala语言，因为Scala语言相对比较简洁。但Java API也是十分类似的（特殊情况，我们将会指出）。在我们的Github仓库里，我们所写的应用程序具有Scala和Java两种版本。</p>
</div>
<div class="sect2">
<h3 id="_你好flink">5.1. 你好，Flink！</h3>
<div class="paragraph">
<p>让我们写一个简单的例子来获得使用DataStream API编写流处理应用程序的粗浅印象。我们将使用这个简单的示例来展示一个Flink程序的基本结构，以及介绍一些DataStream API的重要特性。我们的示例程序摄取了一条（来自多个传感器的）温度测量数据流。</p>
</div>
<div class="paragraph">
<p>首先让我们看一下表示传感器读数的数据结构：</p>
</div>
<div class="listingblock">
<div class="title">SensorSource.scala</div>
<div class="content">
<pre class="pygments highlight"><code data-lang="scala"><span></span><span class="tok-k">case</span> <span class="tok-k">class</span> <span class="tok-nc">SensorReading</span><span class="tok-o">(</span>
  <span class="tok-n">id</span><span class="tok-k">:</span> <span class="tok-kt">String</span><span class="tok-o">,</span>
  <span class="tok-n">timestamp</span><span class="tok-k">:</span> <span class="tok-kt">Long</span><span class="tok-o">,</span>
  <span class="tok-n">temperature</span><span class="tok-k">:</span> <span class="tok-kt">Double</span><span class="tok-o">)</span></code></pre>
</div>
</div>
<div class="paragraph">
<p>示例程序5-1将温度从华氏温度读数转换成摄氏温度读数，然后针对每一个传感器，每5秒钟计算一次平均温度纸。</p>
</div>
<div class="listingblock">
<div class="title">Example5_1.scala</div>
<div class="content">
<pre class="pygments highlight"><code data-lang="scala"><span></span><span class="tok-c1">// Scala object that defines the DataStream program in the main() method.</span>
<span class="tok-k">object</span> <span class="tok-nc">AverageSensorReadings</span> <span class="tok-o">{</span>
  <span class="tok-c1">// main() defines and executes the DataStream program</span>
  <span class="tok-k">def</span> <span class="tok-n">main</span><span class="tok-o">(</span><span class="tok-n">args</span><span class="tok-k">:</span> <span class="tok-kt">Array</span><span class="tok-o">[</span><span class="tok-kt">String</span><span class="tok-o">])</span> <span class="tok-o">{</span>
    <span class="tok-c1">// set up the streaming execution environment</span>
    <span class="tok-k">val</span> <span class="tok-n">env</span> <span class="tok-k">=</span> <span class="tok-nc">StreamExecutionEnvironment</span><span class="tok-o">.</span><span class="tok-n">getExecutionEnvironment</span>
    <span class="tok-c1">// use event time for the application</span>
    <span class="tok-n">env</span><span class="tok-o">.</span><span class="tok-n">setStreamTimeCharacteristic</span><span class="tok-o">(</span><span class="tok-nc">TimeCharacteristic</span><span class="tok-o">.</span><span class="tok-nc">EventTime</span><span class="tok-o">)</span>
    <span class="tok-c1">// create a DataStream[SensorReading] from a stream source</span>
    <span class="tok-k">val</span> <span class="tok-n">sensorData</span><span class="tok-k">:</span> <span class="tok-kt">DataStream</span><span class="tok-o">[</span><span class="tok-kt">SensorReading</span><span class="tok-o">]</span> <span class="tok-k">=</span> <span class="tok-n">env</span>
      <span class="tok-c1">// ingest sensor readings with a SensorSource SourceFunction</span>
      <span class="tok-o">.</span><span class="tok-n">addSource</span><span class="tok-o">(</span><span class="tok-k">new</span> <span class="tok-nc">SensorSource</span><span class="tok-o">)</span>
      <span class="tok-c1">// assign timestamps and watermarks (required for event time)</span>
    <span class="tok-k">val</span> <span class="tok-n">avgTemp</span><span class="tok-k">:</span> <span class="tok-kt">DataStream</span><span class="tok-o">[</span><span class="tok-kt">SensorReading</span><span class="tok-o">]</span> <span class="tok-k">=</span> <span class="tok-n">sensorData</span>
      <span class="tok-c1">// convert Fahrenheit to Celsius with an inline lambda function</span>
      <span class="tok-o">.</span><span class="tok-n">map</span><span class="tok-o">(</span> <span class="tok-n">r</span> <span class="tok-k">=&gt;</span> <span class="tok-o">{</span>
        <span class="tok-k">val</span> <span class="tok-n">celsius</span> <span class="tok-k">=</span> <span class="tok-o">(</span><span class="tok-n">r</span><span class="tok-o">.</span><span class="tok-n">temperature</span> <span class="tok-o">-</span> <span class="tok-mi">32</span><span class="tok-o">)</span> <span class="tok-o">*</span> <span class="tok-o">(</span><span class="tok-mf">5.0</span> <span class="tok-o">/</span> <span class="tok-mf">9.0</span><span class="tok-o">)</span> <span class="tok-nc">SensorReading</span><span class="tok-o">(</span><span class="tok-n">r</span><span class="tok-o">.</span><span class="tok-n">id</span><span class="tok-o">,</span> <span class="tok-n">r</span><span class="tok-o">.</span><span class="tok-n">timestamp</span><span class="tok-o">,</span> <span class="tok-n">celsius</span><span class="tok-o">)</span>
      <span class="tok-o">})</span>
      <span class="tok-c1">// organize readings by sensor id</span>
      <span class="tok-o">.</span><span class="tok-n">keyBy</span><span class="tok-o">(</span><span class="tok-k">_</span><span class="tok-o">.</span><span class="tok-n">id</span><span class="tok-o">)</span>
      <span class="tok-c1">// group readings in 5 second tumbling windows</span>
      <span class="tok-o">.</span><span class="tok-n">timeWindow</span><span class="tok-o">(</span><span class="tok-nc">Time</span><span class="tok-o">.</span><span class="tok-n">seconds</span><span class="tok-o">(</span><span class="tok-mi">5</span><span class="tok-o">))</span>
      <span class="tok-c1">// compute average temperature using a user-defined function</span>
      <span class="tok-o">.</span><span class="tok-n">apply</span><span class="tok-o">(</span><span class="tok-k">new</span> <span class="tok-nc">TemperatureAverager</span><span class="tok-o">)</span>
      <span class="tok-c1">// print result stream to standard out</span>
      <span class="tok-n">avgTemp</span><span class="tok-o">.</span><span class="tok-n">print</span><span class="tok-o">()</span>
    <span class="tok-c1">// execute application</span>
    <span class="tok-n">env</span><span class="tok-o">.</span><span class="tok-n">execute</span><span class="tok-o">(</span><span class="tok-s">&quot;Compute average sensor temperature&quot;</span><span class="tok-o">)</span>
  <span class="tok-o">}</span>
<span class="tok-o">}</span></code></pre>
</div>
</div>
<div class="paragraph">
<p>你可能已经注意到Flink程序的定义和提交执行使用的就是正常的Scala或者Java的方法。大多数情况下，这些代码都写在一个静态main方法中。在我们的例子中，我们定义了AverageSensorReadings对象，然后将大多数的应用程序逻辑放在了main()中。</p>
</div>
<div class="paragraph">
<p>Flink流处理程序的结构如下：</p>
</div>
<div class="olist arabic">
<ol class="arabic">
<li>
<p>创建Flink程序执行环境。</p>
</li>
<li>
<p>从数据源读取一条或者多条流数据</p>
</li>
<li>
<p>使用流转换算子实现业务逻辑</p>
</li>
<li>
<p>将计算结果输出到一个或者多个外部设备（可选）</p>
</li>
<li>
<p>执行程序</p>
</li>
</ol>
</div>
<div class="paragraph">
<p>接下来我们详细的学习一下这些部分。</p>
</div>
</div>
<div class="sect2">
<h3 id="_搭建执行环境">5.2. 搭建执行环境</h3>
<div class="paragraph">
<p>编写Flink程序的第一件事情就是搭建执行环境。执行环境决定了程序是运行在单机上还是集群上。在DataStream API中，程序的执行环境是由StreamExecutionEnvironment设置的。在我们的例子中，我们通过调用静态getExecutionEnvironment()方法来获取执行环境。这个方法根据调用方法的上下文，返回一个本地的或者远程的环境。如果这个方法是一个客户端提交到远程集群的代码调用的，那么这个方法将会返回一个远程的执行环境。否则，将返回本地执行环境。</p>
</div>
<div class="paragraph">
<p>也可以用下面的方法来显式的创建本地或者远程执行环境：</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="pygments highlight"><code data-lang="scala"><span></span><span class="tok-c1">// create a local stream execution environment</span>
<span class="tok-k">val</span> <span class="tok-n">localEnv</span><span class="tok-k">:</span> <span class="tok-kt">StreamExecutionEnvironment.createLocalEnvironment</span><span class="tok-o">()</span>
<span class="tok-c1">// create a remote stream execution environment</span>
<span class="tok-k">val</span> <span class="tok-n">remoteEnv</span> <span class="tok-k">=</span> <span class="tok-nc">StreamExecutionEnvironment</span><span class="tok-o">.</span><span class="tok-n">createRemoteEnvironment</span><span class="tok-o">(</span>
  <span class="tok-s">&quot;host&quot;</span><span class="tok-o">,</span> <span class="tok-c1">// hostname of JobManager</span>
  <span class="tok-mi">1234</span><span class="tok-o">,</span> <span class="tok-c1">// port of JobManager process</span>
  <span class="tok-s">&quot;path/to/jarFile.jar&quot;</span><span class="tok-o">)</span> <span class="tok-c1">// JAR file to ship to the JobManager</span></code></pre>
</div>
</div>
<div class="paragraph">
<p>接下来，我们使用<code>env.setStreamTimeCharacteristic(TimeCharacteristic.EventTime)</code>来将我们程序的时间语义设置为事件时间。执行环境提供了很多配置选项，例如：设置程序的并行度和程序是否开启容错机制。</p>
</div>
</div>
<div class="sect2">
<h3 id="_读取输入流">5.3. 读取输入流</h3>
<div class="paragraph">
<p>一旦执行环境设置好，就该写业务逻辑了。<code>StreamExecutionEnvironment</code>提供了创建数据源的方法，这些方法可以从数据流中将数据摄取到程序中。数据流可以来自消息队列或者文件系统，也可能是实时产生的（例如socket）。</p>
</div>
<div class="paragraph">
<p>在我们的例子里面，我们这样写：</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="pygments highlight"><code data-lang="scala"><span></span><span class="tok-k">val</span> <span class="tok-n">sensorData</span><span class="tok-k">:</span> <span class="tok-kt">DataStream</span><span class="tok-o">[</span><span class="tok-kt">SensorReading</span><span class="tok-o">]</span> <span class="tok-k">=</span> <span class="tok-n">env</span><span class="tok-o">.</span><span class="tok-n">addSource</span><span class="tok-o">(</span><span class="tok-k">new</span> <span class="tok-nc">SensorSource</span><span class="tok-o">)</span></code></pre>
</div>
</div>
<div class="paragraph">
<p>这样就可以连接到传感器测量数据的数据源并创建一个类型为<code>SensorReading</code>的<code>DataStream</code>了。Flink支持很多数据类型，我们将在接下来的章节里面讲解。在我们的例子里面，我们的数据类型是一个定义好的Scala样例类。<code>SensorReading</code>样例类包含了传感器ID，数据的测量时间戳，以及测量温度值。<code>assignTimestampsAndWatermarks(new SensorTimeAssigner)</code>方法指定了如何设置事件时间语义的时间戳和水位线。有关<code>SensorTimeAssigner</code>我们后面再讲。</p>
</div>
</div>
<div class="sect2">
<h3 id="_转换算子的使用">5.4. 转换算子的使用</h3>
<div class="paragraph">
<p>一旦我们有一条DataStream，我们就可以在这条数据流上面使用转换算子了。转换算子有很多种。一些转换算子可以产生一条新的DataStream，当然这个DataStream的类型可能是新类型。还有一些转换算子不会改变原有DataStream的数据，但会将数据流分区或者分组。业务逻辑就是由转换算子串起来组合而成的。</p>
</div>
<div class="paragraph">
<p>在我们的例子中，我们首先使用<code>map()</code>转换算子将传感器的温度值转换成了摄氏温度单位。然后，我们使用<code>keyBy()</code>转换算子将传感器读数流按照传感器ID进行分区。接下来，我们定义了一个<code>timeWindow()</code>转换算子，这个算子将每个传感器ID所对应的分区的传感器读数分配到了5秒钟的滚动窗口中。</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="pygments highlight"><code data-lang="scala"><span></span><span class="tok-k">val</span> <span class="tok-n">avgTemp</span><span class="tok-k">:</span> <span class="tok-kt">DataStream</span><span class="tok-o">[</span><span class="tok-kt">SensorReading</span><span class="tok-o">]</span> <span class="tok-k">=</span> <span class="tok-n">sensorData</span>
  <span class="tok-o">.</span><span class="tok-n">map</span><span class="tok-o">(</span><span class="tok-n">r</span> <span class="tok-k">=&gt;</span> <span class="tok-o">{</span>
    <span class="tok-k">val</span> <span class="tok-n">celsius</span> <span class="tok-k">=</span> <span class="tok-o">(</span><span class="tok-n">r</span><span class="tok-o">.</span><span class="tok-n">temperature</span> <span class="tok-o">-</span> <span class="tok-mi">32</span><span class="tok-o">)</span> <span class="tok-o">*</span> <span class="tok-o">(</span><span class="tok-mf">5.0</span> <span class="tok-o">/</span> <span class="tok-mf">9.0</span><span class="tok-o">)</span>
    <span class="tok-nc">SensorReading</span><span class="tok-o">(</span><span class="tok-n">r</span><span class="tok-o">.</span><span class="tok-n">id</span><span class="tok-o">,</span> <span class="tok-n">r</span><span class="tok-o">.</span><span class="tok-n">timestamp</span><span class="tok-o">,</span> <span class="tok-n">celsius</span><span class="tok-o">)</span>
  <span class="tok-o">})</span>
  <span class="tok-o">.</span><span class="tok-n">keyBy</span><span class="tok-o">(</span><span class="tok-k">_</span><span class="tok-o">.</span><span class="tok-n">id</span><span class="tok-o">)</span>
  <span class="tok-o">.</span><span class="tok-n">timeWindow</span><span class="tok-o">(</span><span class="tok-nc">Time</span><span class="tok-o">.</span><span class="tok-n">seconds</span><span class="tok-o">(</span><span class="tok-mi">5</span><span class="tok-o">))</span>
  <span class="tok-o">.</span><span class="tok-n">apply</span><span class="tok-o">(</span><span class="tok-k">new</span> <span class="tok-nc">TemperatureAverager</span><span class="tok-o">)</span></code></pre>
</div>
</div>
<div class="paragraph">
<p>窗口转换算子将在“窗口操作符”一章中讲解。最后，我们使用了一个UDF函数来计算每个窗口的温度的平均值。我们稍后将会讨论UDF函数的实现。</p>
</div>
</div>
<div class="sect2">
<h3 id="_输出结果">5.5. 输出结果</h3>
<div class="paragraph">
<p>流处理程序经常将它们的计算结果发送到一些外部系统中去，例如：Apache Kafka，文件系统，或者数据库中。Flink提供了一个维护的很好的sink算子的集合，这些sink算子可以用来将数据写入到不同的系统中去。我们也可以实现自己的sink算子。也有一些Flink程序并不会向第三方外部系统发送数据，而是将数据存储到Flink系统内部，然后可以使用Flink的可查询状态的特性来查询数据。</p>
</div>
<div class="paragraph">
<p>在我们的例子中，计算结果是一个<code>DataStream[SensorReading]</code>数据记录。每一条数据记录包含了一个传感器在5秒钟的周期里面的平均温度。计算结果组成的数据流将会调用<code>print()</code>将计算结果写到标准输出。</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="pygments highlight"><code data-lang="scala"><span></span><span class="tok-n">avgTemp</span><span class="tok-o">.</span><span class="tok-n">print</span><span class="tok-o">()</span></code></pre>
</div>
</div>
<div class="admonitionblock note">
<table>
<tr>
<td class="icon">
<i class="fa icon-note" title="Note"></i>
</td>
<td class="content">
要注意一点，流的Sink算子的选择将会影响应用程序端到端(<code>end-to-end</code>)的一致性，具体就是应用程序的计算提供的到底是<code>at-least-once</code>还是<code>exactly-once</code>的一致性语义。应用程序端到端的一致性依赖于所选择的流的Sink算子和Flink的检查点算法的集成使用。
</td>
</tr>
</table>
</div>
</div>
<div class="sect2">
<h3 id="_执行">5.6. 执行</h3>
<div class="paragraph">
<p>当应用程序完全写好时，我们可以调用<code>StreamExecutionEnvironment.execute()</code>来执行应用程序。在我们的例子中就是我们的最后一行调用：</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="pygments highlight"><code data-lang="scala"><span></span><span class="tok-n">env</span><span class="tok-o">.</span><span class="tok-n">execute</span><span class="tok-o">(</span><span class="tok-s">&quot;Compute average sensor temperature&quot;</span><span class="tok-o">)</span></code></pre>
</div>
</div>
<div class="paragraph">
<p>Flink程序是惰性执行的。也就是说创建数据源和转换算子的API调用并不会立刻触发任何数据处理逻辑。API调用仅仅是在执行环境中构建了一个执行计划，这个执行计划包含了执行环境创建的数据源和所有的将要用在数据源上的转换算子。只有当<code>execute()</code>被调用时，系统才会触发程序的执行。</p>
</div>
<div class="paragraph">
<p>构建好的执行计划将被翻译成一个<code>JobGraph</code>并提交到<code>JobManager</code>上面去执行。根据执行环境的种类，一个<code>JobManager</code>将会运行在一个本地线程中（如果是本地执行环境的化）或者<code>JobGraph</code>将会被发送到一个远程的<code>JobManager</code>上面去。如果<code>JobManager</code>远程运行，那么<code>JobGraph</code>必须和一个包含有所有类和应用程序的依赖的JAR包一起发送到远程<code>JobManager</code>。</p>
</div>
</div>
<div class="sect2">
<h3 id="_产生传感器读数代码编写">5.7. 产生传感器读数代码编写</h3>
<div class="sect3">
<h4 id="_从批读取数据">5.7.1. 从批读取数据</h4>
<div class="listingblock">
<div class="content">
<pre class="pygments highlight"><code data-lang="scala"><span></span><span class="tok-k">val</span> <span class="tok-n">stream</span> <span class="tok-k">=</span> <span class="tok-n">env</span>
  <span class="tok-o">.</span><span class="tok-n">fromCollection</span><span class="tok-o">(</span><span class="tok-nc">List</span><span class="tok-o">(</span>
    <span class="tok-nc">SensorReading</span><span class="tok-o">(</span><span class="tok-s">&quot;sensor_1&quot;</span><span class="tok-o">,</span> <span class="tok-mi">1547718199</span><span class="tok-o">,</span> <span class="tok-mf">35.80018327300259</span><span class="tok-o">),</span>
    <span class="tok-nc">SensorReading</span><span class="tok-o">(</span><span class="tok-s">&quot;sensor_6&quot;</span><span class="tok-o">,</span> <span class="tok-mi">1547718199</span><span class="tok-o">,</span> <span class="tok-mf">15.402984393403084</span><span class="tok-o">),</span>
    <span class="tok-nc">SensorReading</span><span class="tok-o">(</span><span class="tok-s">&quot;sensor_7&quot;</span><span class="tok-o">,</span> <span class="tok-mi">1547718199</span><span class="tok-o">,</span> <span class="tok-mf">6.720945201171228</span><span class="tok-o">),</span>
    <span class="tok-nc">SensorReading</span><span class="tok-o">(</span><span class="tok-s">&quot;sensor_10&quot;</span><span class="tok-o">,</span> <span class="tok-mi">1547718199</span><span class="tok-o">,</span> <span class="tok-mf">38.101067604893444</span><span class="tok-o">)</span>
  <span class="tok-o">))</span></code></pre>
</div>
</div>
</div>
<div class="sect3">
<h4 id="_从文件读取数据">5.7.2. 从文件读取数据</h4>
<div class="listingblock">
<div class="content">
<pre class="pygments highlight"><code data-lang="scala"><span></span><span class="tok-k">val</span> <span class="tok-n">stream</span> <span class="tok-k">=</span> <span class="tok-n">env</span><span class="tok-o">.</span><span class="tok-n">readTextFile</span><span class="tok-o">(</span><span class="tok-n">filePath</span><span class="tok-o">)</span></code></pre>
</div>
</div>
</div>
<div class="sect3">
<h4 id="_以kafka消息队列的数据为数据来源">5.7.3. 以Kafka消息队列的数据为数据来源</h4>
<div class="listingblock">
<div class="content">
<pre class="pygments highlight"><code data-lang="scala"><span></span><span class="tok-k">val</span> <span class="tok-n">properties</span> <span class="tok-k">=</span> <span class="tok-k">new</span> <span class="tok-nc">Properties</span><span class="tok-o">()</span>
<span class="tok-n">properties</span><span class="tok-o">.</span><span class="tok-n">setProperty</span><span class="tok-o">(</span><span class="tok-s">&quot;bootstrap.servers&quot;</span><span class="tok-o">,</span> <span class="tok-s">&quot;localhost:9092&quot;</span><span class="tok-o">)</span>
<span class="tok-n">properties</span><span class="tok-o">.</span><span class="tok-n">setProperty</span><span class="tok-o">(</span><span class="tok-s">&quot;group.id&quot;</span><span class="tok-o">,</span> <span class="tok-s">&quot;consumer-group&quot;</span><span class="tok-o">)</span>
<span class="tok-n">properties</span><span class="tok-o">.</span><span class="tok-n">setProperty</span><span class="tok-o">(</span><span class="tok-s">&quot;key.deserializer&quot;</span><span class="tok-o">,</span> <span class="tok-s">&quot;org.apache.kafka.common.serialization.StringDeserializer&quot;</span><span class="tok-o">)</span>
<span class="tok-n">properties</span><span class="tok-o">.</span><span class="tok-n">setProperty</span><span class="tok-o">(</span><span class="tok-s">&quot;value.deserializer&quot;</span><span class="tok-o">,</span> <span class="tok-s">&quot;org.apache.kafka.common.serialization.StringDeserializer&quot;</span><span class="tok-o">)</span>
<span class="tok-n">properties</span><span class="tok-o">.</span><span class="tok-n">setProperty</span><span class="tok-o">(</span><span class="tok-s">&quot;auto.offset.reset&quot;</span><span class="tok-o">,</span> <span class="tok-s">&quot;latest&quot;</span><span class="tok-o">)</span>
<span class="tok-k">val</span> <span class="tok-n">env</span> <span class="tok-k">=</span> <span class="tok-nc">StreamExecutionEnvironment</span><span class="tok-o">.</span><span class="tok-n">getExecutionEnvironment</span>
<span class="tok-n">env</span><span class="tok-o">.</span><span class="tok-n">setStreamTimeCharacteristic</span><span class="tok-o">(</span><span class="tok-nc">TimeCharacteristic</span><span class="tok-o">.</span><span class="tok-nc">EventTime</span><span class="tok-o">)</span>
<span class="tok-n">env</span><span class="tok-o">.</span><span class="tok-n">setParallelism</span><span class="tok-o">(</span><span class="tok-mi">1</span><span class="tok-o">)</span>
<span class="tok-k">val</span> <span class="tok-n">stream</span> <span class="tok-k">=</span> <span class="tok-n">env</span>
  <span class="tok-c1">// source为来自Kafka的数据，这里我们实例化一个消费者，topic为hotitems</span>
  <span class="tok-o">.</span><span class="tok-n">addSource</span><span class="tok-o">(</span><span class="tok-k">new</span> <span class="tok-nc">FlinkKafkaConsumer</span><span class="tok-o">[</span><span class="tok-kt">String</span><span class="tok-o">](</span><span class="tok-s">&quot;hotitems&quot;</span><span class="tok-o">,</span> <span class="tok-k">new</span> <span class="tok-nc">SimpleStringSchema</span><span class="tok-o">(),</span> <span class="tok-n">properties</span><span class="tok-o">))</span></code></pre>
</div>
</div>
<div class="admonitionblock note">
<table>
<tr>
<td class="icon">
<i class="fa icon-note" title="Note"></i>
</td>
<td class="content">
注意，Kafka的版本为<code>2.2</code>。
</td>
</tr>
</table>
</div>
</div>
<div class="sect3">
<h4 id="_自定义数据源">5.7.4. 自定义数据源</h4>
<div class="listingblock">
<div class="title">SensorSource.scala</div>
<div class="content">
<pre class="pygments highlight"><code data-lang="scala"><span></span><span class="tok-k">import</span> <span class="tok-nn">java.util.Calendar</span>

<span class="tok-k">import</span> <span class="tok-nn">org.apache.flink.streaming.api.functions.source.RichParallelSourceFunction</span>
<span class="tok-k">import</span> <span class="tok-nn">org.apache.flink.streaming.api.functions.source.SourceFunction.SourceContext</span>

<span class="tok-k">import</span> <span class="tok-nn">scala.util.Random</span>

<span class="tok-c1">// 传感器id，时间戳，温度</span>
<span class="tok-k">case</span> <span class="tok-k">class</span> <span class="tok-nc">SensorReading</span><span class="tok-o">(</span><span class="tok-n">id</span><span class="tok-k">:</span> <span class="tok-kt">String</span><span class="tok-o">,</span> <span class="tok-n">timestamp</span><span class="tok-k">:</span> <span class="tok-kt">Long</span><span class="tok-o">,</span> <span class="tok-n">temperature</span><span class="tok-k">:</span> <span class="tok-kt">Double</span><span class="tok-o">)</span>

<span class="tok-c1">// 需要extends RichParallelSourceFunction, 泛型为SensorReading</span>
<span class="tok-k">class</span> <span class="tok-nc">SensorSource</span> <span class="tok-k">extends</span> <span class="tok-nc">RichParallelSourceFunction</span><span class="tok-o">[</span><span class="tok-kt">SensorReading</span><span class="tok-o">]</span> <span class="tok-o">{</span>

  <span class="tok-c1">// flag indicating whether source is still running.</span>
  <span class="tok-c1">// flag: 表示数据源是否还在正常运行</span>
  <span class="tok-k">var</span> <span class="tok-n">running</span><span class="tok-k">:</span> <span class="tok-kt">Boolean</span> <span class="tok-o">=</span> <span class="tok-kc">true</span>

  <span class="tok-cm">/** run() continuously emits SensorReadings by emitting them through the SourceContext. */</span>
  <span class="tok-c1">// run()函数连续的发送SensorReading数据，使用SourceContext</span>
  <span class="tok-c1">// 需要override</span>
  <span class="tok-k">override</span> <span class="tok-k">def</span> <span class="tok-n">run</span><span class="tok-o">(</span><span class="tok-n">srcCtx</span><span class="tok-k">:</span> <span class="tok-kt">SourceContext</span><span class="tok-o">[</span><span class="tok-kt">SensorReading</span><span class="tok-o">])</span><span class="tok-k">:</span> <span class="tok-kt">Unit</span> <span class="tok-o">=</span> <span class="tok-o">{</span>

    <span class="tok-c1">// initialize random number generator</span>
    <span class="tok-c1">// 初始化随机数发生器</span>
    <span class="tok-k">val</span> <span class="tok-n">rand</span> <span class="tok-k">=</span> <span class="tok-k">new</span> <span class="tok-nc">Random</span><span class="tok-o">()</span>
    <span class="tok-c1">// look up index of this parallel task</span>
    <span class="tok-c1">// 查找当前运行时上下文的任务的索引</span>
    <span class="tok-k">val</span> <span class="tok-n">taskIdx</span> <span class="tok-k">=</span> <span class="tok-k">this</span><span class="tok-o">.</span><span class="tok-n">getRuntimeContext</span><span class="tok-o">.</span><span class="tok-n">getIndexOfThisSubtask</span>

    <span class="tok-c1">// initialize sensor ids and temperatures</span>
    <span class="tok-c1">// 初始化10个(温度传感器的id, 温度值)元组</span>
    <span class="tok-k">var</span> <span class="tok-n">curFTemp</span> <span class="tok-k">=</span> <span class="tok-o">(</span><span class="tok-mi">1</span> <span class="tok-n">to</span> <span class="tok-mi">10</span><span class="tok-o">).</span><span class="tok-n">map</span> <span class="tok-o">{</span>
      <span class="tok-c1">// nextGaussian产生高斯随机数</span>
      <span class="tok-n">i</span> <span class="tok-k">=&gt;</span> <span class="tok-o">(</span><span class="tok-s">&quot;sensor_&quot;</span> <span class="tok-o">+</span> <span class="tok-o">(</span><span class="tok-n">taskIdx</span> <span class="tok-o">*</span> <span class="tok-mi">10</span> <span class="tok-o">+</span> <span class="tok-n">i</span><span class="tok-o">),</span> <span class="tok-mi">65</span> <span class="tok-o">+</span> <span class="tok-o">(</span><span class="tok-n">rand</span><span class="tok-o">.</span><span class="tok-n">nextGaussian</span><span class="tok-o">()</span> <span class="tok-o">*</span> <span class="tok-mi">20</span><span class="tok-o">))</span>
    <span class="tok-o">}</span>

    <span class="tok-c1">// emit data until being canceled</span>
    <span class="tok-c1">// 无限循环，产生数据流</span>
    <span class="tok-k">while</span> <span class="tok-o">(</span><span class="tok-n">running</span><span class="tok-o">)</span> <span class="tok-o">{</span>

      <span class="tok-c1">// update temperature</span>
      <span class="tok-c1">// 更新温度</span>
      <span class="tok-n">curFTemp</span> <span class="tok-k">=</span> <span class="tok-n">curFTemp</span><span class="tok-o">.</span><span class="tok-n">map</span><span class="tok-o">(</span> <span class="tok-n">t</span> <span class="tok-k">=&gt;</span> <span class="tok-o">(</span><span class="tok-n">t</span><span class="tok-o">.</span><span class="tok-n">_1</span><span class="tok-o">,</span> <span class="tok-n">t</span><span class="tok-o">.</span><span class="tok-n">_2</span> <span class="tok-o">+</span> <span class="tok-o">(</span><span class="tok-n">rand</span><span class="tok-o">.</span><span class="tok-n">nextGaussian</span><span class="tok-o">()</span> <span class="tok-o">*</span> <span class="tok-mf">0.5</span><span class="tok-o">))</span> <span class="tok-o">)</span>
      <span class="tok-c1">// get current time</span>
      <span class="tok-c1">// 获取当前时间戳</span>
      <span class="tok-k">val</span> <span class="tok-n">curTime</span> <span class="tok-k">=</span> <span class="tok-nc">Calendar</span><span class="tok-o">.</span><span class="tok-n">getInstance</span><span class="tok-o">.</span><span class="tok-n">getTimeInMillis</span>

      <span class="tok-c1">// emit new SensorReading</span>
      <span class="tok-c1">// 发射新的传感器数据, 注意这里srcCtx.collect</span>
      <span class="tok-n">curFTemp</span><span class="tok-o">.</span><span class="tok-n">foreach</span><span class="tok-o">(</span> <span class="tok-n">t</span> <span class="tok-k">=&gt;</span> <span class="tok-n">srcCtx</span><span class="tok-o">.</span><span class="tok-n">collect</span><span class="tok-o">(</span><span class="tok-nc">SensorReading</span><span class="tok-o">(</span><span class="tok-n">t</span><span class="tok-o">.</span><span class="tok-n">_1</span><span class="tok-o">,</span> <span class="tok-n">curTime</span><span class="tok-o">,</span> <span class="tok-n">t</span><span class="tok-o">.</span><span class="tok-n">_2</span><span class="tok-o">)))</span>

      <span class="tok-c1">// wait for 100 ms</span>
      <span class="tok-nc">Thread</span><span class="tok-o">.</span><span class="tok-n">sleep</span><span class="tok-o">(</span><span class="tok-mi">100</span><span class="tok-o">)</span>
    <span class="tok-o">}</span>

  <span class="tok-o">}</span>

  <span class="tok-cm">/** Cancels this SourceFunction. */</span>
  <span class="tok-c1">// override cancel函数</span>
  <span class="tok-k">override</span> <span class="tok-k">def</span> <span class="tok-n">cancel</span><span class="tok-o">()</span><span class="tok-k">:</span> <span class="tok-kt">Unit</span> <span class="tok-o">=</span> <span class="tok-o">{</span>
    <span class="tok-n">running</span> <span class="tok-k">=</span> <span class="tok-kc">false</span>
  <span class="tok-o">}</span>

<span class="tok-o">}</span></code></pre>
</div>
</div>
<div class="paragraph">
<p>使用方法</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="pygments highlight"><code data-lang="scala"><span></span><span class="tok-c1">// ingest sensor stream</span>
<span class="tok-k">val</span> <span class="tok-n">sensorData</span><span class="tok-k">:</span> <span class="tok-kt">DataStream</span><span class="tok-o">[</span><span class="tok-kt">SensorReading</span><span class="tok-o">]</span> <span class="tok-k">=</span> <span class="tok-n">env</span>
  <span class="tok-c1">// SensorSource generates random temperature readings</span>
  <span class="tok-o">.</span><span class="tok-n">addSource</span><span class="tok-o">(</span><span class="tok-k">new</span> <span class="tok-nc">SensorSource</span><span class="tok-o">)</span></code></pre>
</div>
</div>
<div class="admonitionblock note">
<table>
<tr>
<td class="icon">
<i class="fa icon-note" title="Note"></i>
</td>
<td class="content">
注意，在我们本教程中，我们一直会使用这个自定义的数据源。
</td>
</tr>
</table>
</div>
</div>
</div>
<div class="sect2">
<h3 id="_转换算子_2">5.8. 转换算子</h3>
<div class="paragraph">
<p>在这一小节我们将大概看一下DataStream API的基本转换算子。与时间有关的操作符（例如窗口操作符和其他特殊的转换算子）将会在后面的章节叙述。一个流的转换操作将会应用在一个或者多个流上面，这些转换操作将流转换成一个或者多个输出流。编写一个DataStream API简单来说就是将这些转换算子组合在一起来构建一个数据流图，这个数据流图就实现了我们的业务逻辑。</p>
</div>
<div class="paragraph">
<p>大部分的流转换操作都基于用户自定义函数UDF。UDF函数打包了一些业务逻辑并定义了输入流的元素如何转换成输出流的元素。像<code>MapFunction</code>这样的函数，将会被定义为类，这个类实现了Flink针对特定的转换操作暴露出来的接口。</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="pygments highlight"><code data-lang="scala"><span></span><span class="tok-k">class</span> <span class="tok-nc">MyMapFunction</span> <span class="tok-k">extends</span> <span class="tok-nc">MapFunction</span><span class="tok-o">[</span><span class="tok-kt">Int</span>, <span class="tok-kt">Int</span><span class="tok-o">]</span> <span class="tok-o">{</span>
  <span class="tok-k">override</span> <span class="tok-k">def</span> <span class="tok-n">map</span><span class="tok-o">(</span><span class="tok-n">value</span><span class="tok-k">:</span> <span class="tok-kt">Int</span><span class="tok-o">)</span><span class="tok-k">:</span> <span class="tok-kt">Int</span> <span class="tok-o">=</span> <span class="tok-n">value</span> <span class="tok-o">+</span> <span class="tok-mi">1</span>
<span class="tok-o">}</span></code></pre>
</div>
</div>
<div class="paragraph">
<p>函数接口定义了需要由用户实现的转换方法，例如上面例子中的<code>map()</code>方法。</p>
</div>
<div class="paragraph">
<p>大部分函数接口被设计为<code>Single Abstract Method</code>（单独抽象方法）接口，并且接口可以使用Java 8匿名函数来实现。Scala DataStream API也内置了对匿名函数的支持。当讲解DataStream API的转换算子时，我们展示了针对所有函数类的接口，但为了简洁，大部分接口的实现使用匿名函数而不是函数类的方式。</p>
</div>
<div class="paragraph">
<p>DataStream API针对大多数数据转换操作提供了转换算子。如果你很熟悉批处理API、函数式编程语言或者SQL，那么你将会发现这些API很容易学习。我们会将DataStream API的转换算子分成四类：</p>
</div>
<div class="olist arabic">
<ol class="arabic">
<li>
<p>基本转换算子：将会作用在数据流中的每一条单独的数据上。</p>
</li>
<li>
<p>KeyedStream转换算子：在数据有key的情况下，对数据应用转换算子。</p>
</li>
<li>
<p>多流转换算子：合并多条流为一条流或者将一条流分割为多条流。</p>
</li>
<li>
<p>分布式转换算子：将重新组织流里面的事件。</p>
</li>
</ol>
</div>
<div class="sect3">
<h4 id="_基本转换算子">5.8.1. 基本转换算子</h4>
<div class="paragraph">
<p>基本转换算子会针对流中的每一个单独的事件做处理，也就是说每一个输入数据会产生一个输出数据。单值转换，数据的分割，数据的过滤，都是基本转换操作的典型例子。我们将解释这些算子的语义并提供示例代码。</p>
</div>
<div class="paragraph">
<p><strong>MAP</strong></p>
</div>
<div class="paragraph">
<p><code>map</code>算子通过调用<code>DataStream.map()</code>来指定。<code>map</code>算子的使用将会产生一条新的数据流。它会将每一个输入的事件传送到一个用户自定义的mapper，这个mapper只返回一个输出事件，这个输出事件和输入事件的类型可能不一样。图5-1展示了一个map算子，这个map将每一个正方形转化成了圆形。</p>
</div>
<div class="imageblock">
<div class="content">
<img src="images/spaf_0501.png" alt="spaf 0501">
</div>
</div>
<div class="paragraph">
<p><code>MapFunction</code>的类型与输入事件和输出事件的类型相关，可以通过实现<code>MapFunction</code>接口来定义。接口包含<code>map()</code>函数，这个函数将一个输入事件恰好转换为一个输出事件。</p>
</div>
<div class="listingblock">
<div class="content">
<pre>// T: the type of input elements
// O: the type of output elements
MapFunction[T, O]
    &gt; map(T): O</pre>
</div>
</div>
<div class="paragraph">
<p>下面的代码实现了将SensorReading中的id字段抽取出来的功能。</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="pygments highlight"><code data-lang="scala"><span></span><span class="tok-k">val</span> <span class="tok-n">readings</span><span class="tok-k">:</span> <span class="tok-kt">DataStream</span><span class="tok-o">[</span><span class="tok-kt">SensorReading</span><span class="tok-o">]</span> <span class="tok-k">=</span> <span class="tok-o">...</span>
<span class="tok-k">val</span> <span class="tok-n">sensorIds</span><span class="tok-k">:</span> <span class="tok-kt">DataStream</span><span class="tok-o">[</span><span class="tok-kt">String</span><span class="tok-o">]</span> <span class="tok-k">=</span> <span class="tok-n">readings</span><span class="tok-o">.</span><span class="tok-n">map</span><span class="tok-o">(</span><span class="tok-k">new</span> <span class="tok-nc">MyMapFunction</span><span class="tok-o">)</span>

<span class="tok-k">class</span> <span class="tok-nc">MyMapFunction</span> <span class="tok-k">extends</span> <span class="tok-nc">MapFunction</span><span class="tok-o">[</span><span class="tok-kt">SensorReading</span>, <span class="tok-kt">String</span><span class="tok-o">]</span> <span class="tok-o">{</span>
  <span class="tok-k">override</span> <span class="tok-k">def</span> <span class="tok-n">map</span><span class="tok-o">(</span><span class="tok-n">r</span><span class="tok-k">:</span> <span class="tok-kt">SensorReading</span><span class="tok-o">)</span><span class="tok-k">:</span> <span class="tok-kt">String</span> <span class="tok-o">=</span> <span class="tok-n">r</span><span class="tok-o">.</span><span class="tok-n">id</span>
<span class="tok-o">}</span></code></pre>
</div>
</div>
<div class="paragraph">
<p>当然我们更推荐匿名函数的写法。</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="pygments highlight"><code data-lang="scala"><span></span><span class="tok-k">val</span> <span class="tok-n">readings</span><span class="tok-k">:</span> <span class="tok-kt">DataStream</span><span class="tok-o">[</span><span class="tok-kt">SensorReading</span><span class="tok-o">]</span> <span class="tok-k">=</span> <span class="tok-o">...</span>
<span class="tok-k">val</span> <span class="tok-n">sensorIds</span><span class="tok-k">:</span> <span class="tok-kt">DataStream</span><span class="tok-o">[</span><span class="tok-kt">String</span><span class="tok-o">]</span> <span class="tok-k">=</span> <span class="tok-n">readings</span><span class="tok-o">.</span><span class="tok-n">map</span><span class="tok-o">(</span><span class="tok-n">r</span> <span class="tok-k">=&gt;</span> <span class="tok-n">r</span><span class="tok-o">.</span><span class="tok-n">id</span><span class="tok-o">)</span></code></pre>
</div>
</div>
<div class="paragraph">
<p><strong>FILTER</strong></p>
</div>
<div class="paragraph">
<p><code>filter</code>转换算子通过在每个输入事件上对一个布尔条件进行求值来过滤掉一些元素，然后将剩下的元素继续发送。一个<code>true</code>的求值结果将会把输入事件保留下来并发送到输出，而如果求值结果为<code>false</code>，则输入事件会被抛弃掉。我们通过调用<code>DataStream.filter()</code>来指定流的<code>filter</code>算子，<code>filter</code>操作将产生一条新的流，其类型和输入流中的事件类型是一样的。图5-2展示了只产生白色方框的<code>filter</code>操作。</p>
</div>
<div class="imageblock">
<div class="content">
<img src="images/spaf_0502.png" alt="spaf 0502">
</div>
</div>
<div class="paragraph">
<p>布尔条件可以使用函数、FilterFunction接口或者匿名函数来实现。FilterFunction中的泛型是输入事件的类型。定义的<code>filter()</code>方法会作用在每一个输入元素上面，并返回一个布尔值。</p>
</div>
<div class="listingblock">
<div class="content">
<pre>// T: the type of elements
FilterFunction[T]
    &gt; filter(T): Boolean</pre>
</div>
</div>
<div class="paragraph">
<p>下面的例子展示了如何使用filter来从传感器数据中过滤掉温度值小于25华氏温度的读数。</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="pygments highlight"><code data-lang="scala"><span></span><span class="tok-k">val</span> <span class="tok-n">readings</span><span class="tok-k">:</span> <span class="tok-kt">DataStream</span><span class="tok-o">[</span><span class="tok-kt">SensorReading</span><span class="tok-o">]</span> <span class="tok-k">=</span> <span class="tok-o">...</span>
<span class="tok-k">val</span> <span class="tok-n">filteredSensors</span> <span class="tok-k">=</span> <span class="tok-n">readings</span><span class="tok-o">.</span><span class="tok-n">filter</span><span class="tok-o">(</span><span class="tok-n">r</span> <span class="tok-k">=&gt;</span> <span class="tok-n">r</span><span class="tok-o">.</span><span class="tok-n">temperature</span> <span class="tok-o">&gt;=</span> <span class="tok-mi">25</span><span class="tok-o">)</span></code></pre>
</div>
</div>
<div class="paragraph">
<p><strong>FLATMAP</strong></p>
</div>
<div class="paragraph">
<p><code>flatMap</code>算子和<code>map</code>算子很类似，不同之处在于针对每一个输入事件<code>flatMap</code>可以生成0个、1个或者多个输出元素。事实上，<code>flatMap</code>转换算子是<code>filter</code>和<code>map</code>的泛化。所以<code>flatMap</code>可以实现<code>map</code>和<code>filter</code>算子的功能。图5-3展示了<code>flatMap</code>如何根据输入事件的颜色来做不同的处理。如果输入事件是白色方框，则直接输出。输入元素是黑框，则复制输入。灰色方框会被过滤掉。</p>
</div>
<div class="imageblock">
<div class="content">
<img src="images/spaf_0503.png" alt="spaf 0503">
</div>
</div>
<div class="paragraph">
<p>flatMap算子将会应用在每一个输入事件上面。对应的<code>FlatMapFunction</code>定义了<code>flatMap()</code>方法，这个方法返回0个、1个或者多个事件到一个<code>Collector</code>集合中，作为输出结果。</p>
</div>
<div class="listingblock">
<div class="content">
<pre>// T: the type of input elements
// O: the type of output elements
FlatMapFunction[T, O]
    &gt; flatMap(T, Collector[O]): Unit</pre>
</div>
</div>
<div class="paragraph">
<p>下面的例子展示了在数据分析教程中经常用到的例子，我们用<code>flatMap</code>来实现。这个函数应用在一个语句流上面，将每个句子用空格切分，然后把切分出来的单词作为单独的事件发送出去。</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="pygments highlight"><code data-lang="scala"><span></span><span class="tok-k">val</span> <span class="tok-n">sentences</span><span class="tok-k">:</span> <span class="tok-kt">DataStream</span><span class="tok-o">[</span><span class="tok-kt">String</span><span class="tok-o">]</span> <span class="tok-k">=</span> <span class="tok-o">...</span>
<span class="tok-k">val</span> <span class="tok-n">words</span><span class="tok-k">:</span> <span class="tok-kt">DataStream</span><span class="tok-o">[</span><span class="tok-kt">String</span><span class="tok-o">]</span> <span class="tok-k">=</span> <span class="tok-n">sentences</span>
  <span class="tok-o">.</span><span class="tok-n">flatMap</span><span class="tok-o">(</span><span class="tok-n">id</span> <span class="tok-k">=&gt;</span> <span class="tok-n">id</span><span class="tok-o">.</span><span class="tok-n">split</span><span class="tok-o">(</span><span class="tok-s">&quot; &quot;</span><span class="tok-o">))</span></code></pre>
</div>
</div>
</div>
<div class="sect3">
<h4 id="_键控流转换算子">5.8.2. 键控流转换算子</h4>
<div class="paragraph">
<p>很多流处理程序的一个基本要求就是要能对数据进行分组，分组后的数据共享某一个相同的属性。DataStream API提供了一个叫做<code>KeyedStream</code>的抽象，此抽象会从逻辑上对DataStream进行分区，分区后的数据拥有同样的<code>Key</code>值，分区后的流互不相关。</p>
</div>
<div class="paragraph">
<p>针对KeyedStream的状态转换操作可以读取数据或者写入数据到当前事件Key所对应的状态中。这表明拥有同样Key的所有事件都可以访问同样的状态，也就是说所以这些事件可以一起处理。</p>
</div>
<div class="admonitionblock note">
<table>
<tr>
<td class="icon">
<i class="fa icon-note" title="Note"></i>
</td>
<td class="content">
要小心使用状态转换操作和基于Key的聚合操作。如果Key的值越来越多，例如：Key是订单ID，我们必须及时清空Key所对应的状态，以免引起内存方面的问题。稍后我们会详细讲解。
</td>
</tr>
</table>
</div>
<div class="paragraph">
<p>KeyedStream可以使用map，flatMap和filter算子来处理。接下来我们会使用keyBy算子来将DataStream转换成KeyedStream，并讲解基于key的转换操作：滚动聚合和reduce算子。</p>
</div>
<div class="paragraph">
<p><strong>KEYBY</strong></p>
</div>
<div class="paragraph">
<p>keyBy通过指定key来将DataStream转换成KeyedStream。基于不同的key，流中的事件将被分配到不同的分区中去。所有具有相同key的事件将会在接下来的操作符的同一个子任务槽中进行处理。拥有不同key的事件可以在同一个任务中处理。但是算子只能访问当前事件的key所对应的状态。</p>
</div>
<div class="paragraph">
<p>如图5-4所示，把输入事件的颜色作为key，黑色的事件输出到了一个分区，其他颜色输出到了另一个分区。</p>
</div>
<div class="imageblock">
<div class="content">
<img src="images/spaf_0504.png" alt="spaf 0504">
</div>
</div>
<div class="paragraph">
<p><code>keyBy()</code>方法接收一个参数，这个参数指定了key或者keys，有很多不同的方法来指定key。我们将在后面讲解。下面的代码声明了<code>id</code>这个字段为SensorReading流的key。</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="pygments highlight"><code data-lang="scala"><span></span><span class="tok-k">val</span> <span class="tok-n">readings</span><span class="tok-k">:</span> <span class="tok-kt">DataStream</span><span class="tok-o">[</span><span class="tok-kt">SensorReading</span><span class="tok-o">]</span> <span class="tok-k">=</span> <span class="tok-o">...</span>
<span class="tok-k">val</span> <span class="tok-n">keyed</span><span class="tok-k">:</span> <span class="tok-kt">KeyedStream</span><span class="tok-o">[</span><span class="tok-kt">SensorReading</span>, <span class="tok-kt">String</span><span class="tok-o">]</span> <span class="tok-k">=</span> <span class="tok-n">readings</span>
  <span class="tok-o">.</span><span class="tok-n">keyBy</span><span class="tok-o">(</span><span class="tok-n">r</span> <span class="tok-k">=&gt;</span> <span class="tok-n">r</span><span class="tok-o">.</span><span class="tok-n">id</span><span class="tok-o">)</span></code></pre>
</div>
</div>
<div class="paragraph">
<p>匿名函数<code>r &#8658; r.id</code>抽取了传感器读数SensorReading的id值。</p>
</div>
<div class="paragraph">
<p><strong>滚动聚合</strong></p>
</div>
<div class="paragraph">
<p>滚动聚合算子由<code>KeyedStream</code>调用，并生成一个聚合以后的DataStream，例如：sum，minimum，maximum。一个滚动聚合算子会为每一个观察到的key保存一个聚合的值。针对每一个输入事件，算子将会更新保存的聚合结果，并发送一个带有更新后的值的事件到下游算子。滚动聚合不需要用户自定义函数，但需要接受一个参数，这个参数指定了在哪一个字段上面做聚合操作。DataStream API提供了以下滚动聚合方法。</p>
</div>
<div class="admonitionblock note">
<table>
<tr>
<td class="icon">
<i class="fa icon-note" title="Note"></i>
</td>
<td class="content">
滚动聚合算子只能用在滚动窗口，不能用在滑动窗口。
</td>
</tr>
</table>
</div>
<div class="ulist">
<ul>
<li>
<p>sum()：在输入流上对指定的字段做滚动相加操作。</p>
</li>
<li>
<p>min()：在输入流上对指定的字段求最小值。</p>
</li>
<li>
<p>max()：在输入流上对指定的字段求最大值。</p>
</li>
<li>
<p>minBy()：在输入流上针对指定字段求最小值，并返回包含当前观察到的最小值的事件。</p>
</li>
<li>
<p>maxBy()：在输入流上针对指定字段求最大值，并返回包含当前观察到的最大值的事件。</p>
</li>
</ul>
</div>
<div class="paragraph">
<p>滚动聚合算子无法组合起来使用，每次计算只能使用一个单独的滚动聚合算子。</p>
</div>
<div class="paragraph">
<p>下面的例子根据第一个字段来对类型为<code>Tuple3[Int, Int, Int]</code>的流做分流操作，然后针对第二个字段做滚动求和操作。</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="pygments highlight"><code data-lang="scala"><span></span><span class="tok-k">val</span> <span class="tok-n">inputStream</span><span class="tok-k">:</span> <span class="tok-kt">DataStream</span><span class="tok-o">[(</span><span class="tok-kt">Int</span>, <span class="tok-kt">Int</span>, <span class="tok-kt">Int</span><span class="tok-o">)]</span> <span class="tok-k">=</span> <span class="tok-n">env</span><span class="tok-o">.</span><span class="tok-n">fromElements</span><span class="tok-o">(</span>
  <span class="tok-o">(</span><span class="tok-mi">1</span><span class="tok-o">,</span> <span class="tok-mi">2</span><span class="tok-o">,</span> <span class="tok-mi">2</span><span class="tok-o">),</span> <span class="tok-o">(</span><span class="tok-mi">2</span><span class="tok-o">,</span> <span class="tok-mi">3</span><span class="tok-o">,</span> <span class="tok-mi">1</span><span class="tok-o">),</span> <span class="tok-o">(</span><span class="tok-mi">2</span><span class="tok-o">,</span> <span class="tok-mi">2</span><span class="tok-o">,</span> <span class="tok-mi">4</span><span class="tok-o">),</span> <span class="tok-o">(</span><span class="tok-mi">1</span><span class="tok-o">,</span> <span class="tok-mi">5</span><span class="tok-o">,</span> <span class="tok-mi">3</span><span class="tok-o">))</span>

<span class="tok-k">val</span> <span class="tok-n">resultStream</span><span class="tok-k">:</span> <span class="tok-kt">DataStream</span><span class="tok-o">[(</span><span class="tok-kt">Int</span>, <span class="tok-kt">Int</span>, <span class="tok-kt">Int</span><span class="tok-o">)]</span> <span class="tok-k">=</span> <span class="tok-n">inputStream</span>
  <span class="tok-o">.</span><span class="tok-n">keyBy</span><span class="tok-o">(</span><span class="tok-mi">0</span><span class="tok-o">)</span> <span class="tok-c1">// key on first field of the tuple</span>
  <span class="tok-o">.</span><span class="tok-n">sum</span><span class="tok-o">(</span><span class="tok-mi">1</span><span class="tok-o">)</span>   <span class="tok-c1">// sum the second field of the tuple in place</span></code></pre>
</div>
</div>
<div class="paragraph">
<p>在这个例子里面，输入流根据第一个字段来分流，然后在第二个字段上做计算。对于key 1，输出结果是(1,2,2),(1,7,2)。对于key 2，输出结果是(2,3,1),(2,5,1)。第一个字段是key，第二个字段是求和的数值，第三个字段未定义。</p>
</div>
<div class="admonitionblock note">
<table>
<tr>
<td class="icon">
<i class="fa icon-note" title="Note"></i>
</td>
<td class="content">
滚动聚合操作会对每一个key都保存一个状态。因为状态从来不会被清空，所以我们在使用滚动聚合算子时只能使用在含有有限个key的流上面。
</td>
</tr>
</table>
</div>
<div class="paragraph">
<p><strong>REDUCE</strong></p>
</div>
<div class="paragraph">
<p>reduce算子是滚动聚合的泛化实现。它将一个ReduceFunction应用到了一个KeyedStream上面去。reduce算子将会把每一个输入事件和当前已经reduce出来的值做聚合计算。reduce操作不会改变流的事件类型。输出流数据类型和输入流数据类型是一样的。</p>
</div>
<div class="paragraph">
<p>reduce函数可以通过实现接口ReduceFunction来创建一个类。ReduceFunction接口定义了<code>reduce()</code>方法，此方法接收两个输入事件，输入一个相同类型的事件。</p>
</div>
<div class="listingblock">
<div class="content">
<pre>// T: the element type
ReduceFunction[T]
    &gt; reduce(T, T): T</pre>
</div>
</div>
<div class="paragraph">
<p>下面的例子，流根据语言这个key来分区，输出结果为针对每一种语言都实时更新的单词列表。</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="pygments highlight"><code data-lang="scala"><span></span><span class="tok-k">val</span> <span class="tok-n">inputStream</span><span class="tok-k">:</span> <span class="tok-kt">DataStream</span><span class="tok-o">[(</span><span class="tok-kt">String</span>, <span class="tok-kt">List</span><span class="tok-o">[</span><span class="tok-kt">String</span><span class="tok-o">])]</span> <span class="tok-k">=</span> <span class="tok-n">env</span><span class="tok-o">.</span><span class="tok-n">fromElements</span><span class="tok-o">(</span>
  <span class="tok-o">(</span><span class="tok-s">&quot;en&quot;</span><span class="tok-o">,</span> <span class="tok-nc">List</span><span class="tok-o">(</span><span class="tok-s">&quot;tea&quot;</span><span class="tok-o">)),</span> <span class="tok-o">(</span><span class="tok-s">&quot;fr&quot;</span><span class="tok-o">,</span> <span class="tok-nc">List</span><span class="tok-o">(</span><span class="tok-s">&quot;vin&quot;</span><span class="tok-o">)),</span> <span class="tok-o">(</span><span class="tok-s">&quot;en&quot;</span><span class="tok-o">,</span> <span class="tok-nc">List</span><span class="tok-o">(</span><span class="tok-s">&quot;cake&quot;</span><span class="tok-o">)))</span>

<span class="tok-k">val</span> <span class="tok-n">resultStream</span><span class="tok-k">:</span> <span class="tok-kt">DataStream</span><span class="tok-o">[(</span><span class="tok-kt">String</span>, <span class="tok-kt">List</span><span class="tok-o">[</span><span class="tok-kt">String</span><span class="tok-o">])]</span> <span class="tok-k">=</span> <span class="tok-n">inputStream</span>
  <span class="tok-o">.</span><span class="tok-n">keyBy</span><span class="tok-o">(</span><span class="tok-mi">0</span><span class="tok-o">)</span>
  <span class="tok-o">.</span><span class="tok-n">reduce</span><span class="tok-o">((</span><span class="tok-n">x</span><span class="tok-o">,</span> <span class="tok-n">y</span><span class="tok-o">)</span> <span class="tok-k">=&gt;</span> <span class="tok-o">(</span><span class="tok-n">x</span><span class="tok-o">.</span><span class="tok-n">_1</span><span class="tok-o">,</span> <span class="tok-n">x</span><span class="tok-o">.</span><span class="tok-n">_2</span> <span class="tok-o">:::</span> <span class="tok-n">y</span><span class="tok-o">.</span><span class="tok-n">_2</span><span class="tok-o">))</span></code></pre>
</div>
</div>
<div class="paragraph">
<p>reduce匿名函数将连续两个tuple的第一个字段(key字段)继续发送出去，然后将两个tuple的第二个字段List[String]连接。</p>
</div>
<div class="admonitionblock note">
<table>
<tr>
<td class="icon">
<i class="fa icon-note" title="Note"></i>
</td>
<td class="content">
reduce作为滚动聚合的泛化实现，同样也要针对每一个key保存状态。因为状态从来不会清空，所以我们需要将reduce算子应用在一个有限key的流上。
</td>
</tr>
</table>
</div>
</div>
<div class="sect3">
<h4 id="_多流转换算子">5.8.3. 多流转换算子</h4>
<div class="paragraph">
<p>许多应用需要摄入多个流并将流合并处理，还可能需要将一条流分割成多条流然后针对每一条流应用不同的业务逻辑。接下来，我们将讨论DataStream API中提供的能够处理多条输入流或者发送多条输出流的操作算子。</p>
</div>
<div class="paragraph">
<p><strong>UNION</strong></p>
</div>
<div class="paragraph">
<p>DataStream.union()方法将两条或者多条DataStream合并成一条具有与输入流相同类型的输出DataStream。接下来的转换算子将会处理输入流中的所有元素。图5-5展示了union操作符如何将黑色和白色的事件流合并成一个单一输出流。</p>
</div>
<div class="imageblock">
<div class="content">
<img src="images/spaf_0505.png" alt="spaf 0505">
</div>
</div>
<div class="paragraph">
<p>事件合流的方式为FIFO方式。操作符并不会产生一个特定顺序的事件流。union操作符也不会进行去重。每一个输入事件都被发送到了下一个操作符。</p>
</div>
<div class="paragraph">
<p>下面的例子展示了如何将三条类型为SensorReading的数据流合并成一条流。</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="pygments highlight"><code data-lang="scala"><span></span><span class="tok-k">val</span> <span class="tok-n">parisStream</span><span class="tok-k">:</span> <span class="tok-kt">DataStream</span><span class="tok-o">[</span><span class="tok-kt">SensorReading</span><span class="tok-o">]</span> <span class="tok-k">=</span> <span class="tok-o">...</span>
<span class="tok-k">val</span> <span class="tok-n">tokyoStream</span><span class="tok-k">:</span> <span class="tok-kt">DataStream</span><span class="tok-o">[</span><span class="tok-kt">SensorReading</span><span class="tok-o">]</span> <span class="tok-k">=</span> <span class="tok-o">...</span>
<span class="tok-k">val</span> <span class="tok-n">rioStream</span><span class="tok-k">:</span> <span class="tok-kt">DataStream</span><span class="tok-o">[</span><span class="tok-kt">SensorReading</span><span class="tok-o">]</span> <span class="tok-k">=</span> <span class="tok-o">...</span>
<span class="tok-k">val</span> <span class="tok-n">allCities</span><span class="tok-k">:</span> <span class="tok-kt">DataStream</span><span class="tok-o">[</span><span class="tok-kt">SensorRreading</span><span class="tok-o">]</span> <span class="tok-k">=</span> <span class="tok-n">parisStream</span>
  <span class="tok-o">.</span><span class="tok-n">union</span><span class="tok-o">(</span><span class="tok-n">tokyoStream</span><span class="tok-o">,</span> <span class="tok-n">rioStream</span><span class="tok-o">)</span></code></pre>
</div>
</div>
<div class="paragraph">
<p><strong>CONNECT, COMAP和COFLATMAP</strong></p>
</div>
<div class="paragraph">
<p>联合两条流的事件是非常常见的流处理需求。例如监控一片森林然后发出高危的火警警报。报警的Application接收两条流，一条是温度传感器传回来的数据，一条是烟雾传感器传回来的数据。当两条流都超过各自的阈值时，报警。</p>
</div>
<div class="paragraph">
<p>DataStream API提供了<code>connect</code>操作来支持以上的应用场景。<code>DataStream.connect()</code>方法接收一条<code>DataStream</code>，然后返回一个<code>ConnectedStreams</code>类型的对象，这个对象表示了两条连接的流。</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="pygments highlight"><code data-lang="scala"><span></span><span class="tok-c1">// first stream</span>
<span class="tok-k">val</span> <span class="tok-n">first</span><span class="tok-k">:</span> <span class="tok-kt">DataStream</span><span class="tok-o">[</span><span class="tok-kt">Int</span><span class="tok-o">]</span> <span class="tok-k">=</span> <span class="tok-o">...</span>
<span class="tok-c1">// second stream</span>
<span class="tok-k">val</span> <span class="tok-n">second</span><span class="tok-k">:</span> <span class="tok-kt">DataStream</span><span class="tok-o">[</span><span class="tok-kt">String</span><span class="tok-o">]</span> <span class="tok-k">=</span> <span class="tok-o">...</span>

<span class="tok-c1">// connect streams</span>
<span class="tok-k">val</span> <span class="tok-n">connected</span><span class="tok-k">:</span> <span class="tok-kt">ConnectedStreams</span><span class="tok-o">[</span><span class="tok-kt">Int</span>, <span class="tok-kt">String</span><span class="tok-o">]</span> <span class="tok-k">=</span> <span class="tok-n">first</span><span class="tok-o">.</span><span class="tok-n">connect</span><span class="tok-o">(</span><span class="tok-n">second</span><span class="tok-o">)</span></code></pre>
</div>
</div>
<div class="paragraph">
<p>ConnectedStreams提供了<code>map()</code>和<code>flatMap()</code>方法，分别需要接收类型为<code>CoMapFunction</code>和<code>CoFlatMapFunction</code>的参数。</p>
</div>
<div class="paragraph">
<p>以上两个函数里面的泛型是第一条流的事件类型和第二条流的事件类型，以及输出流的事件类型。还定义了两个方法，每一个方法针对一条流来调用。<code>map1()</code>和<code>flatMap1()</code>会调用在第一条流的元素上面，<code>map2()</code>和<code>flatMap2()</code>会调用在第二条流的元素上面。</p>
</div>
<div class="listingblock">
<div class="content">
<pre>// IN1: 第一条流的事件类型
// IN2: 第二条流的事件类型
// OUT: 输出流的事件类型
CoMapFunction[IN1, IN2, OUT]
    &gt; map1(IN1): OUT
    &gt; map2(IN2): OUT

CoFlatMapFunction[IN1, IN2, OUT]
    &gt; flatMap1(IN1, Collector[OUT]): Unit
    &gt; flatMap2(IN2, Collector[OUT]): Unit</pre>
</div>
</div>
<div class="admonitionblock note">
<table>
<tr>
<td class="icon">
<i class="fa icon-note" title="Note"></i>
</td>
<td class="content">
函数无法选择读某一条流。我们是无法控制函数中的两个方法的调用顺序的。当一条流中的元素到来时，将会调用相对应的方法。
</td>
</tr>
</table>
</div>
<div class="paragraph">
<p>对两条流做连接查询通常需要这两条流基于某些条件被确定性的路由到操作符中相同的并行实例里面去。在默认情况下，connect()操作将不会对两条流的事件建立任何关系，所以两条流的事件将会随机的被发送到下游的算子实例里面去。这样的行为会产生不确定性的计算结果，显然不是我们想要的。为了针对ConnectedStreams进行确定性的转换操作，connect()方法可以和keyBy()或者broadcast()组合起来使用。我们首先看一下keyBy()的示例。</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="pygments highlight"><code data-lang="scala"><span></span><span class="tok-k">val</span> <span class="tok-n">one</span><span class="tok-k">:</span> <span class="tok-kt">DataStream</span><span class="tok-o">[(</span><span class="tok-kt">Int</span>, <span class="tok-kt">Long</span><span class="tok-o">)]</span> <span class="tok-k">=</span> <span class="tok-o">...</span>
<span class="tok-k">val</span> <span class="tok-n">two</span><span class="tok-k">:</span> <span class="tok-kt">DataStream</span><span class="tok-o">[(</span><span class="tok-kt">Int</span>, <span class="tok-kt">String</span><span class="tok-o">)]</span> <span class="tok-k">=</span> <span class="tok-o">...</span>

<span class="tok-c1">// keyBy two connected streams</span>
<span class="tok-k">val</span> <span class="tok-n">keyedConnect1</span><span class="tok-k">:</span> <span class="tok-kt">ConnectedStreams</span><span class="tok-o">[(</span><span class="tok-kt">Int</span>, <span class="tok-kt">Long</span><span class="tok-o">)</span>, <span class="tok-o">(</span><span class="tok-kt">Int</span>, <span class="tok-kt">String</span><span class="tok-o">)]</span> <span class="tok-k">=</span> <span class="tok-n">one</span>
  <span class="tok-o">.</span><span class="tok-n">connect</span><span class="tok-o">(</span><span class="tok-n">two</span><span class="tok-o">)</span>
  <span class="tok-o">.</span><span class="tok-n">keyBy</span><span class="tok-o">(</span><span class="tok-mi">0</span><span class="tok-o">,</span> <span class="tok-mi">0</span><span class="tok-o">)</span> <span class="tok-c1">// key both input streams on first attribute</span>

<span class="tok-c1">// alternative: connect two keyed streams</span>
<span class="tok-k">val</span> <span class="tok-n">keyedConnect2</span><span class="tok-k">:</span> <span class="tok-kt">ConnectedStreams</span><span class="tok-o">[(</span><span class="tok-kt">Int</span>, <span class="tok-kt">Long</span><span class="tok-o">)</span>, <span class="tok-o">(</span><span class="tok-kt">Int</span>, <span class="tok-kt">String</span><span class="tok-o">)]</span> <span class="tok-k">=</span> <span class="tok-n">one</span><span class="tok-o">.</span><span class="tok-n">keyBy</span><span class="tok-o">(</span><span class="tok-mi">0</span><span class="tok-o">).</span><span class="tok-n">connect</span><span class="tok-o">(</span><span class="tok-n">two</span><span class="tok-o">.</span><span class="tok-n">keyBy</span><span class="tok-o">(</span><span class="tok-mi">0</span><span class="tok-o">))</span></code></pre>
</div>
</div>
<div class="paragraph">
<p>无论使用keyBy()算子操作ConnectedStreams还是使用connect()算子连接两条KeyedStreams，connect()算子会将两条流的含有相同Key的所有事件都发送到相同的算子实例。两条流的key必须是一样的类型和值，就像SQL中的JOIN。在connected和keyed stream上面执行的算子有访问keyed state的权限。</p>
</div>
<div class="paragraph">
<p>下面的例子展示了如何连接一条DataStream和广播过的流。</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="pygments highlight"><code data-lang="scala"><span></span><span class="tok-k">val</span> <span class="tok-n">first</span><span class="tok-k">:</span> <span class="tok-kt">DataStream</span><span class="tok-o">[(</span><span class="tok-kt">Int</span>, <span class="tok-kt">Long</span><span class="tok-o">)]</span> <span class="tok-k">=</span> <span class="tok-o">...</span>
<span class="tok-k">val</span> <span class="tok-n">second</span><span class="tok-k">:</span> <span class="tok-kt">DataStream</span><span class="tok-o">[(</span><span class="tok-kt">Int</span>, <span class="tok-kt">String</span><span class="tok-o">)]</span> <span class="tok-k">=</span> <span class="tok-o">...</span>

<span class="tok-c1">// connect streams with broadcast</span>
<span class="tok-k">val</span> <span class="tok-n">keyedConnect</span><span class="tok-k">:</span> <span class="tok-kt">ConnectedStreams</span><span class="tok-o">[(</span><span class="tok-kt">Int</span>, <span class="tok-kt">Long</span><span class="tok-o">)</span>, <span class="tok-o">(</span><span class="tok-kt">Int</span>, <span class="tok-kt">String</span><span class="tok-o">)]</span> <span class="tok-k">=</span> <span class="tok-n">first</span>
  <span class="tok-c1">// broadcast second input stream</span>
  <span class="tok-o">.</span><span class="tok-n">connect</span><span class="tok-o">(</span><span class="tok-n">second</span><span class="tok-o">.</span><span class="tok-n">broadcast</span><span class="tok-o">())</span></code></pre>
</div>
</div>
<div class="paragraph">
<p>一条被广播过的流中的所有元素将会被复制然后发送到下游算子的所有并行实例中去。未被广播过的流仅仅向前发送。所以两条流的元素显然会被连接处理。</p>
</div>
<div class="paragraph">
<p><strong>SPLIT和SELECT</strong></p>
</div>
<div class="paragraph">
<p>Split是Union的反函数。Split将输入的流分成两条或者多条流。每一个输入的元素都可以被路由到0、1或者多条流中去。所以，split可以用来过滤或者复制元素。图5-6展示了split操作符将所有的白色事件都路由到同一条流中去了，剩下的元素去往另一条流。</p>
</div>
<div class="imageblock">
<div class="content">
<img src="images/spaf_0506.png" alt="spaf 0506">
</div>
</div>
<div class="paragraph">
<p>DataStream.split()方法接受<code>OutputSelector</code>类型，此类型定义了输入流中的元素被分配到哪个名字的流中去。<code>OutputSelector</code>定义了<code>select()</code>方法，此方法将被每一个元素调用，并返回<code>java.lang.Iterable[String]</code>类型的数据。返回的<code>String</code>类型的值将指定元素将被路由到哪一条流。</p>
</div>
<div class="listingblock">
<div class="content">
<pre>// IN: the type of the split elements
OutputSelector[IN]
    &gt; select(IN): Iterable[String]</pre>
</div>
</div>
<div class="paragraph">
<p>DataStream.split()方法返回<code>SplitStream</code>类型，此类型提供<code>select()</code>方法，可以根据分流后不同流的名字，将某个名字对应的流提取出来。</p>
</div>
<div class="paragraph">
<p>例5-2将一条整数流分成了不同的流，大的整数一条流，小的整数一条流。</p>
</div>
<div class="listingblock">
<div class="title">Example5_2.scala</div>
<div class="content">
<pre class="pygments highlight"><code data-lang="scala"><span></span><span class="tok-k">val</span> <span class="tok-n">inputStream</span><span class="tok-k">:</span> <span class="tok-kt">DataStream</span><span class="tok-o">[(</span><span class="tok-kt">Int</span>, <span class="tok-kt">String</span><span class="tok-o">)]</span> <span class="tok-k">=</span> <span class="tok-o">...</span>

<span class="tok-k">val</span> <span class="tok-n">splitted</span><span class="tok-k">:</span> <span class="tok-kt">SplitStream</span><span class="tok-o">[(</span><span class="tok-kt">Int</span>, <span class="tok-kt">String</span><span class="tok-o">)]</span> <span class="tok-k">=</span> <span class="tok-n">inputStream</span>
  <span class="tok-o">.</span><span class="tok-n">split</span><span class="tok-o">(</span><span class="tok-n">t</span> <span class="tok-k">=&gt;</span> <span class="tok-k">if</span> <span class="tok-o">(</span><span class="tok-n">t</span><span class="tok-o">.</span><span class="tok-n">_1</span> <span class="tok-o">&gt;</span> <span class="tok-mi">1000</span><span class="tok-o">)</span> <span class="tok-nc">Seq</span><span class="tok-o">(</span><span class="tok-s">&quot;large&quot;</span><span class="tok-o">)</span> <span class="tok-k">else</span> <span class="tok-nc">Seq</span><span class="tok-o">(</span><span class="tok-s">&quot;small&quot;</span><span class="tok-o">))</span>

<span class="tok-k">val</span> <span class="tok-n">large</span><span class="tok-k">:</span> <span class="tok-kt">DataStream</span><span class="tok-o">[(</span><span class="tok-kt">Int</span>, <span class="tok-kt">String</span><span class="tok-o">)]</span> <span class="tok-k">=</span> <span class="tok-n">splitted</span><span class="tok-o">.</span><span class="tok-n">select</span><span class="tok-o">(</span><span class="tok-s">&quot;large&quot;</span><span class="tok-o">)</span>
<span class="tok-k">val</span> <span class="tok-n">small</span><span class="tok-k">:</span> <span class="tok-kt">DataStream</span><span class="tok-o">[(</span><span class="tok-kt">Int</span>, <span class="tok-kt">String</span><span class="tok-o">)]</span> <span class="tok-k">=</span> <span class="tok-n">splitted</span><span class="tok-o">.</span><span class="tok-n">select</span><span class="tok-o">(</span><span class="tok-s">&quot;small&quot;</span><span class="tok-o">)</span>
<span class="tok-k">val</span> <span class="tok-n">all</span><span class="tok-k">:</span> <span class="tok-kt">DataStream</span><span class="tok-o">[(</span><span class="tok-kt">Int</span>, <span class="tok-kt">String</span><span class="tok-o">)]</span> <span class="tok-k">=</span> <span class="tok-n">splitted</span><span class="tok-o">.</span><span class="tok-n">select</span><span class="tok-o">(</span><span class="tok-s">&quot;small&quot;</span><span class="tok-o">,</span> <span class="tok-s">&quot;large&quot;</span><span class="tok-o">)</span></code></pre>
</div>
</div>
<div class="admonitionblock note">
<table>
<tr>
<td class="icon">
<i class="fa icon-note" title="Note"></i>
</td>
<td class="content">
不推荐使用split方法，推荐使用Flink的侧输出（side-output）特性。
</td>
</tr>
</table>
</div>
</div>
<div class="sect3">
<h4 id="_分布式转换算子">5.8.4. 分布式转换算子</h4>
<div class="paragraph">
<p>分区操作对应于我们之前讲过的“数据交换策略”这一节。这些操作定义了事件如何分配到不同的任务中去。当我们使用DataStream API来编写程序时，系统将自动的选择数据分区策略，然后根据操作符的语义和设置的并行度将数据路由到正确的地方去。有些时候，我们需要在应用程序的层面控制分区策略，或者自定义分区策略。例如，如果我们知道会发生数据倾斜，那么我们想要针对数据流做负载均衡，将数据流平均发送到接下来的操作符中去。又或者，应用程序的业务逻辑可能需要一个算子所有的并行任务都需要接收同样的数据。再或者，我们需要自定义分区策略的时候。在这一小节，我们将展示DataStream的一些方法，可以使我们来控制或者自定义数据分区策略。</p>
</div>
<div class="admonitionblock note">
<table>
<tr>
<td class="icon">
<i class="fa icon-note" title="Note"></i>
</td>
<td class="content">
keyBy()方法不同于分布式转换算子。所有的分布式转换算子将产生DataStream数据类型。而keyBy()产生的类型是KeyedStream，它拥有自己的keyed state。
</td>
</tr>
</table>
</div>
<div class="paragraph">
<p><strong>Random</strong></p>
</div>
<div class="paragraph">
<p>随机数据交换由<code>DataStream.shuffle()</code>方法实现。shuffle方法将数据随机的分配到下游算子的并行任务中去。</p>
</div>
<div class="paragraph">
<p><strong>Round-Robin</strong></p>
</div>
<div class="paragraph">
<p><code>rebalance()</code>方法使用Round-Robin负载均衡算法将输入流平均分配到随后的并行运行的任务中去。图5-7为round-robin分布式转换算子的示意图。</p>
</div>
<div class="paragraph">
<p><strong>Rescale</strong></p>
</div>
<div class="paragraph">
<p><code>rescale()</code>方法使用的也是round-robin算法，但只会将数据发送到接下来的并行运行的任务中的一部分任务中。本质上，当发送者任务数量和接收者任务数量不一样时，rescale分区策略提供了一种轻量级的负载均衡策略。如果接收者任务的数量是发送者任务的数量的倍数时，rescale操作将会效率更高。</p>
</div>
<div class="paragraph">
<p><code>rebalance()</code>和<code>rescale()</code>的根本区别在于任务之间连接的机制不同。 <code>rebalance()</code>将会针对所有发送者任务和所有接收者任务之间建立通信通道，而<code>rescale()</code>仅仅针对每一个任务和下游算子的一部分子并行任务之间建立通信通道。rescale的示意图为图5-7。</p>
</div>
<div class="imageblock">
<div class="content">
<img src="images/spaf_0507.png" alt="spaf 0507">
</div>
</div>
<div class="paragraph">
<p><strong>Broadcast</strong></p>
</div>
<div class="paragraph">
<p><code>broadcast()</code>方法将输入流的所有数据复制并发送到下游算子的所有并行任务中去。</p>
</div>
<div class="paragraph">
<p><strong>Global</strong></p>
</div>
<div class="paragraph">
<p><code>global()</code>方法将所有的输入流数据都发送到下游算子的第一个并行任务中去。这个操作需要很谨慎，因为将所有数据发送到同一个task，将会对应用程序造成很大的压力。</p>
</div>
<div class="paragraph">
<p><strong>Custom</strong></p>
</div>
<div class="paragraph">
<p>当Flink提供的分区策略都不适用时，我们可以使用<code>partitionCustom()</code>方法来自定义分区策略。这个方法接收一个<code>Partitioner</code>对象，这个对象需要实现分区逻辑以及定义针对流的哪一个字段或者key来进行分区。下面的例子将一条整数流做partition，使得所有的负整数都发送到第一个任务中，剩下的数随机分配。</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="pygments highlight"><code data-lang="scala"><span></span><span class="tok-k">val</span> <span class="tok-n">numbers</span><span class="tok-k">:</span> <span class="tok-kt">DataStream</span><span class="tok-o">[(</span><span class="tok-kt">Int</span><span class="tok-o">)]</span> <span class="tok-k">=</span> <span class="tok-o">...</span>
<span class="tok-n">numbers</span><span class="tok-o">.</span><span class="tok-n">partitionCustom</span><span class="tok-o">(</span><span class="tok-n">myPartitioner</span><span class="tok-o">,</span> <span class="tok-mi">0</span><span class="tok-o">)</span>

<span class="tok-k">object</span> <span class="tok-nc">myPartitioner</span> <span class="tok-k">extends</span> <span class="tok-nc">Partitioner</span><span class="tok-o">[</span><span class="tok-kt">Int</span><span class="tok-o">]</span> <span class="tok-o">{</span>
  <span class="tok-k">val</span> <span class="tok-n">r</span> <span class="tok-k">=</span> <span class="tok-n">scala</span><span class="tok-o">.</span><span class="tok-n">util</span><span class="tok-o">.</span><span class="tok-nc">Random</span>

  <span class="tok-k">override</span> <span class="tok-k">def</span> <span class="tok-n">partition</span><span class="tok-o">(</span><span class="tok-n">key</span><span class="tok-k">:</span> <span class="tok-kt">Int</span><span class="tok-o">,</span> <span class="tok-n">numPartitions</span><span class="tok-k">:</span> <span class="tok-kt">Int</span><span class="tok-o">)</span><span class="tok-k">:</span> <span class="tok-kt">Int</span> <span class="tok-o">=</span> <span class="tok-o">{</span>
    <span class="tok-k">if</span> <span class="tok-o">(</span><span class="tok-n">key</span> <span class="tok-o">&lt;</span> <span class="tok-mi">0</span><span class="tok-o">)</span> <span class="tok-mi">0</span> <span class="tok-k">else</span> <span class="tok-n">r</span><span class="tok-o">.</span><span class="tok-n">nextInt</span><span class="tok-o">(</span><span class="tok-n">numPartitions</span><span class="tok-o">)</span>
  <span class="tok-o">}</span>
<span class="tok-o">}</span></code></pre>
</div>
</div>
</div>
</div>
<div class="sect2">
<h3 id="_设置并行度">5.9. 设置并行度</h3>
<div class="paragraph">
<p>Flink应用程序在一个像集群这样的分布式环境中并行执行。当一个数据流程序提交到JobManager执行时，系统将会创建一个数据流图，然后准备执行需要的操作符。每一个操作符将会并行化到一个或者多个任务中去。每个算子的并行任务都会处理这个算子的输入流中的一份子集。一个算子并行任务的个数叫做算子的并行度。它决定了算子执行的并行化程度，以及这个算子能处理多少数据量。</p>
</div>
<div class="paragraph">
<p>算子的并行度可以在执行环境这个层级来控制，也可以针对每个不同的算子设置不同的并行度。默认情况下，应用程序中所有算子的并行度都将设置为执行环境的并行度。执行环境的并行度（也就是所有算子的默认并行度）将在程序开始运行时自动初始化。如果应用程序在本地执行环境中运行，并行度将被设置为CPU的核数。当我们把应用程序提交到一个处于运行中的Flink集群时，执行环境的并行度将被设置为集群默认的并行度，除非我们在客户端提交应用程序时显式的设置好并行度。</p>
</div>
<div class="paragraph">
<p>通常情况下，将算子的并行度定义为和执行环境并行度相关的数值会是个好主意。这允许我们通过在客户端调整应用程序的并行度就可以将程序水平扩展了。我们可以使用以下代码来访问执行环境的默认并行度。</p>
</div>
<div class="paragraph">
<p>我们还可以重写执行环境的默认并行度，但这样的话我们将再也不能通过客户端来控制应用程序的并行度了。</p>
</div>
<div class="paragraph">
<p>算子默认的并行度也可以通过重写来明确指定。在下面的例子里面，数据源的操作符将会按照环境默认的并行度来并行执行，map操作符的并行度将会是默认并行度的2倍，sink操作符的并行度为2。</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="pygments highlight"><code data-lang="scala"><span></span><span class="tok-k">val</span> <span class="tok-n">env</span> <span class="tok-k">=</span> <span class="tok-nc">StreamExecutionEnvironment</span><span class="tok-o">.</span><span class="tok-n">getExecutionEnvironment</span>
<span class="tok-k">val</span> <span class="tok-n">defaultP</span> <span class="tok-k">=</span> <span class="tok-n">env</span><span class="tok-o">.</span><span class="tok-n">getParallelism</span>
<span class="tok-k">val</span> <span class="tok-n">result</span> <span class="tok-k">=</span> <span class="tok-n">env</span><span class="tok-o">.</span><span class="tok-n">addSource</span><span class="tok-o">(</span><span class="tok-k">new</span> <span class="tok-nc">CustomSource</span><span class="tok-o">)</span>
  <span class="tok-o">.</span><span class="tok-n">map</span><span class="tok-o">(</span><span class="tok-k">new</span> <span class="tok-nc">MyMapper</span><span class="tok-o">).</span><span class="tok-n">setParallelism</span><span class="tok-o">(</span><span class="tok-n">defaultP</span> <span class="tok-o">*</span> <span class="tok-mi">2</span><span class="tok-o">)</span>
  <span class="tok-o">.</span><span class="tok-n">print</span><span class="tok-o">().</span><span class="tok-n">setParallelism</span><span class="tok-o">(</span><span class="tok-mi">2</span><span class="tok-o">)</span></code></pre>
</div>
</div>
<div class="paragraph">
<p>当我们通过客户端将应用程序的并行度设置为16并提交执行时，source操作符的并行度为16，mapper并行度为32，sink并行度为2。如果我们在本地环境运行应用程序的话，例如在IDE中运行，机器是8核，那么source任务将会并行执行在8个任务上面，mapper运行在16个任务上面，sink运行在2个任务上面。</p>
</div>
</div>
<div class="sect2">
<h3 id="_类型">5.10. 类型</h3>
<div class="paragraph">
<p>Flink程序所处理的流中的事件一般是对象类型。操作符接收对象输出对象。所以Flink的内部机制需要能够处理事件的类型。在网络中传输数据，或者将数据写入到状态后端、检查点和保存点中，都需要我们对数据进行序列化和反序列化。为了高效的进行此类操作，Flink需要流中事件类型的详细信息。Flink使用了<code>Type Information</code>的概念来表达数据类型，这样就能针对不同的数据类型产生特定的序列化器，反序列化器和比较操作符。</p>
</div>
<div class="admonitionblock note">
<table>
<tr>
<td class="icon">
<i class="fa icon-note" title="Note"></i>
</td>
<td class="content">
有点像泛型。
</td>
</tr>
</table>
</div>
<div class="paragraph">
<p>Flink也能够通过分析输入数据和输出数据来自动获取数据的类型信息以及序列化器和反序列化器。尽管如此，在一些特定的情况下，例如匿名函数或者使用泛型的情况下，我们需要明确的提供数据的类型信息，来提高我们程序的性能。</p>
</div>
<div class="paragraph">
<p>在这一节中，我们将讨论Flink支持的类型，以及如何为数据类型创建相应的类型信息，还有就是在Flink无法推断函数返回类型的情况下，如何帮助Flink的类型系统去做类型推断。</p>
</div>
<div class="sect3">
<h4 id="_支持的数据类型">5.10.1. 支持的数据类型</h4>
<div class="paragraph">
<p>Flink支持Java和Scala提供的所有普通数据类型。最常用的数据类型可以做以下分类：</p>
</div>
<div class="ulist">
<ul>
<li>
<p>Primitives（原始数据类型）</p>
</li>
<li>
<p>Java和Scala的Tuples（元组）</p>
</li>
<li>
<p>Scala的样例类</p>
</li>
<li>
<p>POJO类型</p>
</li>
<li>
<p>一些特殊的类型</p>
</li>
</ul>
</div>
<div class="paragraph">
<p>接下来让我们一探究竟。</p>
</div>
<div class="paragraph">
<p><strong>Primitives</strong></p>
</div>
<div class="paragraph">
<p>Java和Scala提供的所有原始数据类型都支持，例如<code>Int</code>(Java的<code>Integer</code>)，String，Double等等。下面举一个例子：</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="pygments highlight"><code data-lang="scala"><span></span><span class="tok-k">val</span> <span class="tok-n">numbers</span><span class="tok-k">:</span> <span class="tok-kt">DataStream</span><span class="tok-o">[</span><span class="tok-kt">Long</span><span class="tok-o">]</span> <span class="tok-k">=</span> <span class="tok-n">env</span><span class="tok-o">.</span><span class="tok-n">fromElements</span><span class="tok-o">(</span><span class="tok-mi">1L</span><span class="tok-o">,</span> <span class="tok-mi">2L</span><span class="tok-o">,</span> <span class="tok-mi">3L</span><span class="tok-o">,</span> <span class="tok-mi">4L</span><span class="tok-o">)</span>
<span class="tok-n">numbers</span><span class="tok-o">.</span><span class="tok-n">map</span><span class="tok-o">(</span><span class="tok-n">n</span> <span class="tok-k">=&gt;</span> <span class="tok-n">n</span> <span class="tok-o">+</span> <span class="tok-mi">1</span><span class="tok-o">)</span></code></pre>
</div>
</div>
<div class="paragraph">
<p><strong>Tuples</strong></p>
</div>
<div class="paragraph">
<p>元组是一种组合数据类型，由固定数量的元素组成。</p>
</div>
<div class="paragraph">
<p>DataStream的Scala API直接使用Scala内置的Tuple。举个例子：</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="pygments highlight"><code data-lang="scala"><span></span><span class="tok-k">val</span> <span class="tok-n">persons</span><span class="tok-k">:</span> <span class="tok-kt">DataStream</span><span class="tok-o">[(</span><span class="tok-kt">String</span>, <span class="tok-kt">Integer</span><span class="tok-o">)]</span> <span class="tok-k">=</span>
<span class="tok-n">env</span><span class="tok-o">.</span><span class="tok-n">fromElements</span><span class="tok-o">(</span>
  <span class="tok-o">(</span><span class="tok-s">&quot;Adam&quot;</span><span class="tok-o">,</span> <span class="tok-mi">17</span><span class="tok-o">),</span>
  <span class="tok-o">(</span><span class="tok-s">&quot;Sarah&quot;</span><span class="tok-o">,</span> <span class="tok-mi">23</span><span class="tok-o">)</span>
<span class="tok-o">)</span>

<span class="tok-n">persons</span><span class="tok-o">.</span><span class="tok-n">filter</span><span class="tok-o">(</span><span class="tok-n">p</span> <span class="tok-k">=&gt;</span> <span class="tok-n">p</span><span class="tok-o">.</span><span class="tok-n">_2</span> <span class="tok-o">&gt;</span> <span class="tok-mi">18</span><span class="tok-o">)</span></code></pre>
</div>
</div>
<div class="paragraph">
<p>Flink为Java的Tuple同样提供了高效的实现。Flink实现的Java Tuple最多可以有25个元素，根据元素数量的不同，Tuple都被实现成了不同的类：Tuple1，Tuple2，一直到Tuple25。Tuple类是强类型。</p>
</div>
<div class="paragraph">
<p>我们可以将上面的例子用Java的DataStream API重写：</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="pygments highlight"><code data-lang="java"><span></span><span class="tok-n">DataStream</span><span class="tok-o">&lt;</span><span class="tok-n">Tuple2</span><span class="tok-o">&lt;</span><span class="tok-n">String</span><span class="tok-o">,</span> <span class="tok-n">Integer</span><span class="tok-o">&gt;&gt;</span> <span class="tok-n">persons</span> <span class="tok-o">=</span> <span class="tok-n">env</span>
  <span class="tok-o">.</span><span class="tok-na">fromElements</span><span class="tok-o">(</span>
    <span class="tok-n">Tuple2</span><span class="tok-o">.</span><span class="tok-na">of</span><span class="tok-o">(</span><span class="tok-s">&quot;Adam&quot;</span><span class="tok-o">,</span> <span class="tok-mi">17</span><span class="tok-o">),</span>
    <span class="tok-n">Tuple2</span><span class="tok-o">.</span><span class="tok-na">of</span><span class="tok-o">(</span><span class="tok-s">&quot;Sarah&quot;</span><span class="tok-o">,</span> <span class="tok-mi">23</span><span class="tok-o">)</span>
  <span class="tok-o">);</span>

<span class="tok-n">persons</span><span class="tok-o">.</span><span class="tok-na">filter</span><span class="tok-o">(</span><span class="tok-n">p</span> <span class="tok-o">-&gt;</span> <span class="tok-n">p</span><span class="tok-o">.</span><span class="tok-na">f1</span> <span class="tok-o">&gt;</span> <span class="tok-mi">18</span><span class="tok-o">);</span></code></pre>
</div>
</div>
<div class="paragraph">
<p>Tuple的元素可以通过它们的public属性访问&#8212;&#8203;f0，f1，f2等等。或者使用<code>getField(int pos)</code>方法来访问，元素下标从0开始：</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="pygments highlight"><code data-lang="java"><span></span><span class="tok-kn">import</span> <span class="tok-nn">org.apache.flink.api.java.tuple.Tuple2</span>

<span class="tok-n">Tuple2</span><span class="tok-o">&lt;</span><span class="tok-n">String</span><span class="tok-o">,</span> <span class="tok-n">Integer</span><span class="tok-o">&gt;</span> <span class="tok-n">personTuple</span> <span class="tok-o">=</span> <span class="tok-n">Tuple2</span><span class="tok-o">.</span><span class="tok-na">of</span><span class="tok-o">(</span><span class="tok-s">&quot;Alex&quot;</span><span class="tok-o">,</span> <span class="tok-mi">42</span><span class="tok-o">);</span>
<span class="tok-n">Integer</span> <span class="tok-n">age</span> <span class="tok-o">=</span> <span class="tok-n">personTuple</span><span class="tok-o">.</span><span class="tok-na">getField</span><span class="tok-o">(</span><span class="tok-mi">1</span><span class="tok-o">);</span> <span class="tok-c1">// age = 42</span></code></pre>
</div>
</div>
<div class="paragraph">
<p>不同于Scala的Tuple，Java的Tuple是可变数据结构，所以Tuple中的元素可以重新进行赋值。重复利用Java的Tuple可以减轻垃圾收集的压力。举个例子：</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="pygments highlight"><code data-lang="java"><span></span><span class="tok-n">personTuple</span><span class="tok-o">.</span><span class="tok-na">f1</span> <span class="tok-o">=</span> <span class="tok-mi">42</span><span class="tok-o">;</span> <span class="tok-c1">// set the 2nd field to 42</span>
<span class="tok-n">personTuple</span><span class="tok-o">.</span><span class="tok-na">setField</span><span class="tok-o">(</span><span class="tok-mi">43</span><span class="tok-o">,</span> <span class="tok-mi">1</span><span class="tok-o">);</span> <span class="tok-c1">// set the 2nd field to 43</span></code></pre>
</div>
</div>
<div class="paragraph">
<p><strong>Scala case classes</strong></p>
</div>
<div class="listingblock">
<div class="content">
<pre class="pygments highlight"><code data-lang="scala"><span></span><span class="tok-k">case</span> <span class="tok-k">class</span> <span class="tok-nc">Person</span><span class="tok-o">(</span><span class="tok-n">name</span><span class="tok-k">:</span> <span class="tok-kt">String</span><span class="tok-o">,</span> <span class="tok-n">age</span><span class="tok-k">:</span> <span class="tok-kt">Int</span><span class="tok-o">)</span>

<span class="tok-k">val</span> <span class="tok-n">persons</span><span class="tok-k">:</span> <span class="tok-kt">DataStream</span><span class="tok-o">[</span><span class="tok-kt">Person</span><span class="tok-o">]</span> <span class="tok-k">=</span> <span class="tok-n">env</span><span class="tok-o">.</span><span class="tok-n">fromElements</span><span class="tok-o">(</span>
  <span class="tok-nc">Person</span><span class="tok-o">(</span><span class="tok-s">&quot;Adam&quot;</span><span class="tok-o">,</span> <span class="tok-mi">17</span><span class="tok-o">),</span>
  <span class="tok-nc">Person</span><span class="tok-o">(</span><span class="tok-s">&quot;Sarah&quot;</span><span class="tok-o">,</span> <span class="tok-mi">23</span><span class="tok-o">)</span>
<span class="tok-o">)</span>

<span class="tok-n">persons</span><span class="tok-o">.</span><span class="tok-n">filter</span><span class="tok-o">(</span><span class="tok-n">p</span> <span class="tok-k">=&gt;</span> <span class="tok-n">p</span><span class="tok-o">.</span><span class="tok-n">age</span> <span class="tok-o">&gt;</span> <span class="tok-mi">18</span><span class="tok-o">)</span></code></pre>
</div>
</div>
<div class="paragraph">
<p><strong>POJO</strong></p>
</div>
<div class="paragraph">
<p>POJO类的定义：</p>
</div>
<div class="ulist">
<ul>
<li>
<p>公有类</p>
</li>
<li>
<p>无参数的公有构造器</p>
</li>
<li>
<p>所有的字段都是公有的，可以通过getters和setters访问。</p>
</li>
<li>
<p>所有字段的数据类型都必须是Flink支持的数据类型。</p>
</li>
</ul>
</div>
<div class="paragraph">
<p>举个例子：</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="pygments highlight"><code data-lang="java"><span></span><span class="tok-kd">public</span> <span class="tok-kd">class</span> <span class="tok-nc">Person</span> <span class="tok-o">{</span>
  <span class="tok-kd">public</span> <span class="tok-n">String</span> <span class="tok-n">name</span><span class="tok-o">;</span>
  <span class="tok-kd">public</span> <span class="tok-kt">int</span> <span class="tok-n">age</span><span class="tok-o">;</span>

  <span class="tok-kd">public</span> <span class="tok-nf">Person</span><span class="tok-o">()</span> <span class="tok-o">{}</span>

  <span class="tok-kd">public</span> <span class="tok-nf">Person</span><span class="tok-o">(</span><span class="tok-n">String</span> <span class="tok-n">name</span><span class="tok-o">,</span> <span class="tok-kt">int</span> <span class="tok-n">age</span><span class="tok-o">)</span> <span class="tok-o">{</span>
    <span class="tok-k">this</span><span class="tok-o">.</span><span class="tok-na">name</span> <span class="tok-o">=</span> <span class="tok-n">name</span><span class="tok-o">;</span>
    <span class="tok-k">this</span><span class="tok-o">.</span><span class="tok-na">age</span> <span class="tok-o">=</span> <span class="tok-n">age</span><span class="tok-o">;</span>
  <span class="tok-o">}</span>
<span class="tok-o">}</span>

<span class="tok-n">DataStream</span><span class="tok-o">&lt;</span><span class="tok-n">Person</span><span class="tok-o">&gt;</span> <span class="tok-n">persons</span> <span class="tok-o">=</span> <span class="tok-n">env</span><span class="tok-o">.</span><span class="tok-na">fromElements</span><span class="tok-o">(</span>
  <span class="tok-k">new</span> <span class="tok-n">Person</span><span class="tok-o">(</span><span class="tok-s">&quot;Alex&quot;</span><span class="tok-o">,</span> <span class="tok-mi">42</span><span class="tok-o">),</span>
  <span class="tok-k">new</span> <span class="tok-n">Person</span><span class="tok-o">(</span><span class="tok-s">&quot;Wendy&quot;</span><span class="tok-o">,</span> <span class="tok-mi">23</span><span class="tok-o">)</span>
<span class="tok-o">);</span></code></pre>
</div>
</div>
<div class="paragraph">
<p><strong>其他数据类型</strong></p>
</div>
<div class="ulist">
<ul>
<li>
<p>Array, ArrayList, HashMap, Enum</p>
</li>
<li>
<p>Hadoop Writable types</p>
</li>
<li>
<p>Either, Option, Try</p>
</li>
</ul>
</div>
</div>
<div class="sect3">
<h4 id="_为数据类型创建类型信息">5.10.2. 为数据类型创建类型信息</h4>
<div class="paragraph">
<p>Flink类型系统的核心类是<code>TypeInformation</code>。它为系统在产生序列化器和比较操作符时，提供了必要的类型信息。例如，如果我们想使用某个key来做联结查询或者分组操作，<code>TypeInformation</code>可以让Flink做更严格的类型检查。</p>
</div>
<div class="paragraph">
<p>Flink针对Java和Scala分别提供了类来产生类型信息。在Java中，类是<code>org.apache.flink.api.common.typeinfo.Types</code>，举个例子：</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="pygments highlight"><code data-lang="java"><span></span><span class="tok-n">TypeInformation</span><span class="tok-o">&lt;</span><span class="tok-n">Integer</span><span class="tok-o">&gt;</span> <span class="tok-n">intType</span> <span class="tok-o">=</span> <span class="tok-n">Types</span><span class="tok-o">.</span><span class="tok-na">INT</span><span class="tok-o">;</span>

<span class="tok-n">TypeInformation</span><span class="tok-o">&lt;</span><span class="tok-n">Tuple2</span><span class="tok-o">&lt;</span><span class="tok-n">Long</span><span class="tok-o">,</span> <span class="tok-n">String</span><span class="tok-o">&gt;&gt;</span> <span class="tok-n">tupleType</span> <span class="tok-o">=</span> <span class="tok-n">Types</span><span class="tok-o">.</span><span class="tok-na">TUPLE</span><span class="tok-o">(</span><span class="tok-n">Types</span><span class="tok-o">.</span><span class="tok-na">LONG</span><span class="tok-o">,</span> <span class="tok-n">Types</span><span class="tok-o">.</span><span class="tok-na">STRING</span><span class="tok-o">);</span>

<span class="tok-n">TypeInformation</span><span class="tok-o">&lt;</span><span class="tok-n">Person</span><span class="tok-o">&gt;</span> <span class="tok-n">personType</span> <span class="tok-o">=</span> <span class="tok-n">Types</span><span class="tok-o">.</span><span class="tok-na">POJO</span><span class="tok-o">(</span><span class="tok-n">Person</span><span class="tok-o">.</span><span class="tok-na">class</span><span class="tok-o">);</span></code></pre>
</div>
</div>
<div class="paragraph">
<p>在Scala中，类是<code>org.apache.flink.api.scala.typeutils.Types</code>，举个例子：</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="pygments highlight"><code data-lang="scala"><span></span><span class="tok-c1">// TypeInformation for primitive types</span>
<span class="tok-k">val</span> <span class="tok-n">stringType</span><span class="tok-k">:</span> <span class="tok-kt">TypeInformation</span><span class="tok-o">[</span><span class="tok-kt">String</span><span class="tok-o">]</span> <span class="tok-k">=</span> <span class="tok-nc">Types</span><span class="tok-o">.</span><span class="tok-nc">STRING</span>
<span class="tok-c1">// TypeInformation for Scala Tuples</span>
<span class="tok-k">val</span> <span class="tok-n">tupleType</span><span class="tok-k">:</span> <span class="tok-kt">TypeInformation</span><span class="tok-o">[(</span><span class="tok-kt">Int</span>, <span class="tok-kt">Long</span><span class="tok-o">)]</span> <span class="tok-k">=</span> <span class="tok-nc">Types</span><span class="tok-o">.</span><span class="tok-nc">TUPLE</span><span class="tok-o">[(</span><span class="tok-kt">Int</span>, <span class="tok-kt">Long</span><span class="tok-o">)]</span>
<span class="tok-c1">// TypeInformation for case classes</span>
<span class="tok-k">val</span> <span class="tok-n">caseClassType</span><span class="tok-k">:</span> <span class="tok-kt">TypeInformation</span><span class="tok-o">[</span><span class="tok-kt">Person</span><span class="tok-o">]</span> <span class="tok-k">=</span> <span class="tok-nc">Types</span><span class="tok-o">.</span><span class="tok-nc">CASE_CLASS</span><span class="tok-o">[</span><span class="tok-kt">Person</span><span class="tok-o">]</span></code></pre>
</div>
</div>
<div class="admonitionblock note">
<table>
<tr>
<td class="icon">
<i class="fa icon-note" title="Note"></i>
</td>
<td class="content">
别忘了导入<code>import org.apache.flink.streaming.api.scala._</code>
</td>
</tr>
</table>
</div>
</div>
</div>
<div class="sect2">
<h3 id="_定义key以及引用字段">5.11. 定义Key以及引用字段</h3>
<div class="paragraph">
<p>在Flink中，我们必须明确指定输入流中的元素中的哪一个字段是key。</p>
</div>
<div class="sect3">
<h4 id="_使用字段位置进行keyby">5.11.1. 使用字段位置进行keyBy</h4>
<div class="listingblock">
<div class="content">
<pre class="pygments highlight"><code data-lang="scala"><span></span><span class="tok-k">val</span> <span class="tok-n">input</span><span class="tok-k">:</span> <span class="tok-kt">DataStream</span><span class="tok-o">[(</span><span class="tok-kt">Int</span>, <span class="tok-kt">String</span>, <span class="tok-kt">Long</span><span class="tok-o">)]</span> <span class="tok-k">=</span> <span class="tok-o">...</span>
<span class="tok-k">val</span> <span class="tok-n">keyed</span> <span class="tok-k">=</span> <span class="tok-n">input</span><span class="tok-o">.</span><span class="tok-n">keyBy</span><span class="tok-o">(</span><span class="tok-mi">1</span><span class="tok-o">)</span></code></pre>
</div>
</div>
<div class="admonitionblock note">
<table>
<tr>
<td class="icon">
<i class="fa icon-note" title="Note"></i>
</td>
<td class="content">
注意，要么明确写清楚类型注释，要么让Scala去做类型推断，不要用IDEA的类型推断功能。
</td>
</tr>
</table>
</div>
<div class="paragraph">
<p>如果我们想要用元组的第2个字段和第3个字段做keyBy，可以看下面的例子。</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="pygments highlight"><code data-lang="scala"><span></span><span class="tok-k">val</span> <span class="tok-n">keyed2</span> <span class="tok-k">=</span> <span class="tok-n">input</span><span class="tok-o">.</span><span class="tok-n">keyBy</span><span class="tok-o">(</span><span class="tok-mi">1</span><span class="tok-o">,</span> <span class="tok-mi">2</span><span class="tok-o">)</span></code></pre>
</div>
</div>
</div>
<div class="sect3">
<h4 id="_使用字段表达式来进行keyby">5.11.2. 使用字段表达式来进行keyBy</h4>
<div class="paragraph">
<p>对于样例类：</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="pygments highlight"><code data-lang="scala"><span></span><span class="tok-k">case</span> <span class="tok-k">class</span> <span class="tok-nc">SensorReading</span><span class="tok-o">(</span>
  <span class="tok-n">id</span><span class="tok-k">:</span> <span class="tok-kt">String</span><span class="tok-o">,</span>
  <span class="tok-n">timestamp</span><span class="tok-k">:</span> <span class="tok-kt">Long</span><span class="tok-o">,</span>
  <span class="tok-n">temperature</span><span class="tok-k">:</span> <span class="tok-kt">Double</span>
<span class="tok-o">)</span>

<span class="tok-k">val</span> <span class="tok-n">sensorStream</span><span class="tok-k">:</span> <span class="tok-kt">DataStream</span><span class="tok-o">[</span><span class="tok-kt">SensorReading</span><span class="tok-o">]</span> <span class="tok-k">=</span> <span class="tok-o">...</span>
<span class="tok-k">val</span> <span class="tok-n">keyedSensors</span> <span class="tok-k">=</span> <span class="tok-n">sensorStream</span><span class="tok-o">.</span><span class="tok-n">keyBy</span><span class="tok-o">(</span><span class="tok-s">&quot;id&quot;</span><span class="tok-o">)</span></code></pre>
</div>
</div>
<div class="paragraph">
<p>对于元组：</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="pygments highlight"><code data-lang="scala"><span></span><span class="tok-k">val</span> <span class="tok-n">input</span><span class="tok-k">:</span> <span class="tok-kt">DataStream</span><span class="tok-o">[(</span><span class="tok-kt">Int</span>, <span class="tok-kt">String</span>, <span class="tok-kt">Long</span><span class="tok-o">)]</span> <span class="tok-k">=</span> <span class="tok-o">...</span>
<span class="tok-k">val</span> <span class="tok-n">keyed1</span> <span class="tok-k">=</span> <span class="tok-n">input</span><span class="tok-o">.</span><span class="tok-n">keyBy</span><span class="tok-o">(</span><span class="tok-s">&quot;2&quot;</span><span class="tok-o">)</span> <span class="tok-c1">// key by 3rd field</span>
<span class="tok-k">val</span> <span class="tok-n">keyed2</span> <span class="tok-k">=</span> <span class="tok-n">input</span><span class="tok-o">.</span><span class="tok-n">keyBy</span><span class="tok-o">(</span><span class="tok-s">&quot;_1&quot;</span><span class="tok-o">)</span> <span class="tok-c1">// key by 1st field</span>

<span class="tok-nc">DataStream</span><span class="tok-o">&lt;</span><span class="tok-nc">Tuple3</span><span class="tok-o">&lt;</span><span class="tok-nc">Integer</span><span class="tok-o">,</span> <span class="tok-nc">String</span><span class="tok-o">,</span> <span class="tok-nc">Long</span><span class="tok-o">&gt;&gt;</span> <span class="tok-n">javaInput</span> <span class="tok-k">=</span> <span class="tok-o">...</span>
<span class="tok-n">javaInput</span><span class="tok-o">.</span><span class="tok-n">keyBy</span><span class="tok-o">(</span><span class="tok-s">&quot;f2&quot;</span><span class="tok-o">)</span> <span class="tok-c1">// key Java tuple by 3rd field</span></code></pre>
</div>
</div>
<div class="paragraph">
<p>对于存在嵌套的样例类：</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="pygments highlight"><code data-lang="scala"><span></span><span class="tok-k">case</span> <span class="tok-k">class</span> <span class="tok-nc">Address</span> <span class="tok-o">(</span>
  <span class="tok-n">address</span><span class="tok-k">:</span> <span class="tok-kt">String</span><span class="tok-o">,</span>
  <span class="tok-n">zip</span><span class="tok-k">:</span> <span class="tok-kt">String</span><span class="tok-o">,</span>
  <span class="tok-n">country</span><span class="tok-k">:</span> <span class="tok-kt">String</span>
<span class="tok-o">)</span>

<span class="tok-k">case</span> <span class="tok-k">class</span> <span class="tok-nc">Person</span> <span class="tok-o">(</span>
  <span class="tok-n">name</span><span class="tok-k">:</span> <span class="tok-kt">String</span><span class="tok-o">,</span>
  <span class="tok-n">birthday</span><span class="tok-k">:</span> <span class="tok-o">(</span><span class="tok-kt">Int</span><span class="tok-o">,</span> <span class="tok-kt">Int</span><span class="tok-o">,</span> <span class="tok-nc">Int</span><span class="tok-o">),</span> <span class="tok-c1">// year, month, day</span>
  <span class="tok-n">address</span><span class="tok-k">:</span> <span class="tok-kt">Address</span>
<span class="tok-o">)</span>

<span class="tok-k">val</span> <span class="tok-n">persons</span><span class="tok-k">:</span> <span class="tok-kt">DataStream</span><span class="tok-o">[</span><span class="tok-kt">Person</span><span class="tok-o">]</span> <span class="tok-k">=</span> <span class="tok-o">...</span>
<span class="tok-n">persons</span><span class="tok-o">.</span><span class="tok-n">keyBy</span><span class="tok-o">(</span><span class="tok-s">&quot;address.zip&quot;</span><span class="tok-o">)</span> <span class="tok-c1">// key by nested POJO field</span>
<span class="tok-n">persons</span><span class="tok-o">.</span><span class="tok-n">keyBy</span><span class="tok-o">(</span><span class="tok-s">&quot;birthday._1&quot;</span><span class="tok-o">)</span> <span class="tok-c1">// key by field of nested tuple</span>
<span class="tok-n">persons</span><span class="tok-o">.</span><span class="tok-n">keyBy</span><span class="tok-o">(</span><span class="tok-s">&quot;birthday._&quot;</span><span class="tok-o">)</span> <span class="tok-c1">// key by all fields of nested tuple</span></code></pre>
</div>
</div>
</div>
<div class="sect3">
<h4 id="_key选择器">5.11.3. Key选择器</h4>
<div class="paragraph">
<p>方法类型</p>
</div>
<div class="listingblock">
<div class="content">
<pre>KeySelector[IN, KEY]
  &gt; getKey(IN): KEY</pre>
</div>
</div>
<div class="paragraph">
<p>两个例子</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="pygments highlight"><code data-lang="scala"><span></span><span class="tok-k">val</span> <span class="tok-n">sensorData</span><span class="tok-k">:</span> <span class="tok-kt">DataStream</span><span class="tok-o">[</span><span class="tok-kt">SensorReading</span><span class="tok-o">]</span> <span class="tok-k">=</span> <span class="tok-o">...</span>
<span class="tok-k">val</span> <span class="tok-n">byId</span><span class="tok-k">:</span> <span class="tok-kt">KeyedStream</span><span class="tok-o">[</span><span class="tok-kt">SensorReading</span>, <span class="tok-kt">String</span><span class="tok-o">]</span> <span class="tok-k">=</span> <span class="tok-n">sensorData</span><span class="tok-o">.</span><span class="tok-n">keyBy</span><span class="tok-o">(</span><span class="tok-n">r</span> <span class="tok-k">=&gt;</span> <span class="tok-n">r</span><span class="tok-o">.</span><span class="tok-n">id</span><span class="tok-o">)</span></code></pre>
</div>
</div>
<div class="listingblock">
<div class="content">
<pre class="pygments highlight"><code data-lang="scala"><span></span><span class="tok-k">val</span> <span class="tok-n">input</span><span class="tok-k">:</span> <span class="tok-kt">DataStream</span><span class="tok-o">[(</span><span class="tok-kt">Int</span>, <span class="tok-kt">Int</span><span class="tok-o">)]</span> <span class="tok-k">=</span> <span class="tok-o">...</span>
<span class="tok-k">val</span> <span class="tok-n">keyedStream</span> <span class="tok-k">=</span> <span class="tok-n">input</span><span class="tok-o">.</span><span class="tok-n">keyBy</span><span class="tok-o">(</span><span class="tok-n">value</span> <span class="tok-k">=&gt;</span> <span class="tok-n">math</span><span class="tok-o">.</span><span class="tok-n">max</span><span class="tok-o">(</span><span class="tok-n">value</span><span class="tok-o">.</span><span class="tok-n">_1</span><span class="tok-o">,</span> <span class="tok-n">value</span><span class="tok-o">.</span><span class="tok-n">_2</span><span class="tok-o">))</span></code></pre>
</div>
</div>
</div>
</div>
<div class="sect2">
<h3 id="_实现udf函数更细粒度的控制流">5.12. 实现UDF函数，更细粒度的控制流</h3>
<div class="sect3">
<h4 id="_函数类function_classes">5.12.1. 函数类(Function Classes)</h4>
<div class="paragraph">
<p>Flink暴露了所有udf函数的接口(实现方式为接口或者抽象类)。例如MapFunction, FilterFunction, ProcessFunction等等。</p>
</div>
<div class="paragraph">
<p>例子实现了FilterFunction接口</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="pygments highlight"><code data-lang="scala"><span></span><span class="tok-k">class</span> <span class="tok-nc">FilterFilter</span> <span class="tok-k">extends</span> <span class="tok-nc">FilterFunction</span><span class="tok-o">[</span><span class="tok-kt">String</span><span class="tok-o">]</span> <span class="tok-o">{</span>
  <span class="tok-k">override</span> <span class="tok-k">def</span> <span class="tok-n">filter</span><span class="tok-o">(</span><span class="tok-n">value</span><span class="tok-k">:</span> <span class="tok-kt">String</span><span class="tok-o">)</span><span class="tok-k">:</span> <span class="tok-kt">Boolean</span> <span class="tok-o">=</span> <span class="tok-o">{</span>
    <span class="tok-n">value</span><span class="tok-o">.</span><span class="tok-n">contains</span><span class="tok-o">(</span><span class="tok-s">&quot;flink&quot;</span><span class="tok-o">)</span>
  <span class="tok-o">}</span>
<span class="tok-o">}</span>

<span class="tok-k">val</span> <span class="tok-n">flinkTweets</span> <span class="tok-k">=</span> <span class="tok-n">tweets</span><span class="tok-o">.</span><span class="tok-n">filter</span><span class="tok-o">(</span><span class="tok-k">new</span> <span class="tok-nc">FlinkFilter</span><span class="tok-o">)</span></code></pre>
</div>
</div>
<div class="paragraph">
<p>还可以将函数实现成匿名类</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="pygments highlight"><code data-lang="scala"><span></span><span class="tok-k">val</span> <span class="tok-n">flinkTweets</span> <span class="tok-k">=</span> <span class="tok-n">tweets</span><span class="tok-o">.</span><span class="tok-n">filter</span><span class="tok-o">(</span>
  <span class="tok-k">new</span> <span class="tok-nc">RichFilterFunction</span><span class="tok-o">[</span><span class="tok-kt">String</span><span class="tok-o">]</span> <span class="tok-o">{</span>
    <span class="tok-k">override</span> <span class="tok-k">def</span> <span class="tok-n">filter</span><span class="tok-o">(</span><span class="tok-n">value</span><span class="tok-k">:</span> <span class="tok-kt">String</span><span class="tok-o">)</span><span class="tok-k">:</span> <span class="tok-kt">Boolean</span> <span class="tok-o">=</span> <span class="tok-o">{</span>
      <span class="tok-n">value</span><span class="tok-o">.</span><span class="tok-n">contains</span><span class="tok-o">(</span><span class="tok-s">&quot;flink&quot;</span><span class="tok-o">)</span>
    <span class="tok-o">}</span>
  <span class="tok-o">}</span>
<span class="tok-o">)</span></code></pre>
</div>
</div>
<div class="paragraph">
<p>我们filter的字符串"flink"还可以当作参数传进去。</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="pygments highlight"><code data-lang="scala"><span></span><span class="tok-k">val</span> <span class="tok-n">tweets</span><span class="tok-k">:</span> <span class="tok-kt">DataStream</span><span class="tok-o">[</span><span class="tok-kt">String</span><span class="tok-o">]</span> <span class="tok-k">=</span> <span class="tok-o">...</span>
<span class="tok-k">val</span> <span class="tok-n">flinkTweets</span> <span class="tok-k">=</span> <span class="tok-n">tweets</span><span class="tok-o">.</span><span class="tok-n">filter</span><span class="tok-o">(</span><span class="tok-k">new</span> <span class="tok-nc">KeywordFilter</span><span class="tok-o">(</span><span class="tok-s">&quot;flink&quot;</span><span class="tok-o">))</span>

<span class="tok-k">class</span> <span class="tok-nc">KeywordFilter</span><span class="tok-o">(</span><span class="tok-n">keyWord</span><span class="tok-k">:</span> <span class="tok-kt">String</span><span class="tok-o">)</span> <span class="tok-k">extends</span> <span class="tok-nc">FilterFunction</span><span class="tok-o">[</span><span class="tok-kt">String</span><span class="tok-o">]</span> <span class="tok-o">{</span>
  <span class="tok-k">override</span> <span class="tok-k">def</span> <span class="tok-n">filter</span><span class="tok-o">(</span><span class="tok-n">value</span><span class="tok-k">:</span> <span class="tok-kt">String</span><span class="tok-o">)</span><span class="tok-k">:</span> <span class="tok-kt">Boolean</span> <span class="tok-o">=</span> <span class="tok-o">{</span>
    <span class="tok-n">value</span><span class="tok-o">.</span><span class="tok-n">contains</span><span class="tok-o">(</span><span class="tok-n">keyWord</span><span class="tok-o">)</span>
  <span class="tok-o">}</span>
<span class="tok-o">}</span></code></pre>
</div>
</div>
</div>
<div class="sect3">
<h4 id="_匿名函数lambda_functions">5.12.2. 匿名函数(Lambda Functions)</h4>
<div class="paragraph">
<p>匿名函数可以实现一些简单的逻辑，但无法实现一些高级功能，例如访问状态等等。</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="pygments highlight"><code data-lang="scala"><span></span><span class="tok-k">val</span> <span class="tok-n">tweets</span><span class="tok-k">:</span> <span class="tok-kt">DataStream</span><span class="tok-o">[</span><span class="tok-kt">String</span><span class="tok-o">]</span> <span class="tok-k">=</span> <span class="tok-o">...</span>
<span class="tok-k">val</span> <span class="tok-n">flinkTweets</span> <span class="tok-k">=</span> <span class="tok-n">tweets</span><span class="tok-o">.</span><span class="tok-n">filter</span><span class="tok-o">(</span><span class="tok-k">_</span><span class="tok-o">.</span><span class="tok-n">contains</span><span class="tok-o">(</span><span class="tok-s">&quot;flink&quot;</span><span class="tok-o">))</span></code></pre>
</div>
</div>
</div>
<div class="sect3">
<h4 id="_富函数rich_functions">5.12.3. 富函数(Rich Functions)</h4>
<div class="paragraph">
<p>我们经常会有这样的需求：在函数处理数据之前，需要做一些初始化的工作；或者需要在处理数据时可以获得函数执行上下文的一些信息；以及在处理完数据时做一些清理工作。而DataStream API就提供了这样的机制。</p>
</div>
<div class="paragraph">
<p>DataStream API提供的所有转换操作函数，都拥有它们的“富”版本，并且我们在使用常规函数或者匿名函数的地方来使用富函数。例如下面就是富函数的一些例子，可以看出，只需要在常规函数的前面加上<code>Rich</code>前缀就是富函数了。</p>
</div>
<div class="ulist">
<ul>
<li>
<p>RichMapFunction</p>
</li>
<li>
<p>RichFlatMapFunction</p>
</li>
<li>
<p>RichFilterFunction</p>
</li>
<li>
<p>&#8230;&#8203;</p>
</li>
</ul>
</div>
<div class="paragraph">
<p>当我们使用富函数时，我们可以实现两个额外的方法：</p>
</div>
<div class="ulist">
<ul>
<li>
<p>open()方法是rich function的初始化方法，当一个算子例如map或者filter被调用之前open()会被调用。open()函数通常用来做一些只需要做一次即可的初始化工作。</p>
</li>
<li>
<p>close()方法是生命周期中的最后一个调用的方法，通常用来做一些清理工作。</p>
</li>
</ul>
</div>
<div class="paragraph">
<p>另外，getRuntimeContext()方法提供了函数的RuntimeContext的一些信息，例如函数执行的并行度，当前子任务的索引，当前子任务的名字。同时还它还包含了访问<strong>分区状态</strong>的方法。下面看一个例子：</p>
</div>
<div class="listingblock">
<div class="title">Example5_3</div>
<div class="content">
<pre class="pygments highlight"><code data-lang="scala"><span></span><span class="tok-k">class</span> <span class="tok-nc">MyFlatMap</span> <span class="tok-k">extends</span> <span class="tok-nc">RichFlatMapFunction</span><span class="tok-o">[</span><span class="tok-kt">Int</span>, <span class="tok-o">(</span><span class="tok-kt">Int</span>, <span class="tok-kt">Int</span><span class="tok-o">)]</span> <span class="tok-o">{</span>
  <span class="tok-k">var</span> <span class="tok-n">subTaskIndex</span> <span class="tok-k">=</span> <span class="tok-mi">0</span>

  <span class="tok-k">override</span> <span class="tok-k">def</span> <span class="tok-n">open</span><span class="tok-o">(</span><span class="tok-n">configuration</span><span class="tok-k">:</span> <span class="tok-kt">Configuration</span><span class="tok-o">)</span><span class="tok-k">:</span> <span class="tok-kt">Unit</span> <span class="tok-o">=</span> <span class="tok-o">{</span>
    <span class="tok-n">subTaskIndex</span> <span class="tok-k">=</span> <span class="tok-n">getRuntimeContext</span><span class="tok-o">.</span><span class="tok-n">getIndexOfThisSubtask</span>
    <span class="tok-c1">// 做一些初始化工作</span>
    <span class="tok-c1">// 例如建立一个和HDFS的连接</span>
  <span class="tok-o">}</span>

  <span class="tok-k">override</span> <span class="tok-k">def</span> <span class="tok-n">flatMap</span><span class="tok-o">(</span><span class="tok-n">in</span><span class="tok-k">:</span> <span class="tok-kt">Int</span><span class="tok-o">,</span> <span class="tok-n">out</span><span class="tok-k">:</span> <span class="tok-kt">Collector</span><span class="tok-o">[(</span><span class="tok-kt">Int</span>, <span class="tok-kt">Int</span><span class="tok-o">)])</span><span class="tok-k">:</span> <span class="tok-kt">Unit</span> <span class="tok-o">=</span> <span class="tok-o">{</span>
    <span class="tok-k">if</span> <span class="tok-o">(</span><span class="tok-n">in</span> <span class="tok-o">%</span> <span class="tok-mi">2</span> <span class="tok-o">==</span> <span class="tok-n">subTaskIndex</span><span class="tok-o">)</span> <span class="tok-o">{</span>
      <span class="tok-n">out</span><span class="tok-o">.</span><span class="tok-n">collect</span><span class="tok-o">((</span><span class="tok-n">subTaskIndex</span><span class="tok-o">,</span> <span class="tok-n">in</span><span class="tok-o">))</span>
    <span class="tok-o">}</span>
  <span class="tok-o">}</span>

  <span class="tok-k">override</span> <span class="tok-k">def</span> <span class="tok-n">close</span><span class="tok-o">()</span><span class="tok-k">:</span> <span class="tok-kt">Unit</span> <span class="tok-o">=</span> <span class="tok-o">{</span>
    <span class="tok-c1">// 清理工作，断开和HDFS的连接。</span>
  <span class="tok-o">}</span>
<span class="tok-o">}</span></code></pre>
</div>
</div>
</div>
</div>
<div class="sect2">
<h3 id="_sink">5.13. Sink</h3>
<div class="paragraph">
<p>Flink没有类似于spark中foreach方法，让用户进行迭代的操作。虽有对外的输出操作都要利用Sink完成。最后通过类似如下方式完成整个任务最终输出操作。</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="pygments highlight"><code data-lang="scala"><span></span><span class="tok-n">stream</span><span class="tok-o">.</span><span class="tok-n">addSink</span><span class="tok-o">(</span><span class="tok-k">new</span> <span class="tok-nc">MySink</span><span class="tok-o">(</span><span class="tok-n">xxxx</span><span class="tok-o">))</span></code></pre>
</div>
</div>
<div class="paragraph">
<p>官方提供了一部分的框架的sink。除此以外，需要用户自定义实现sink。</p>
</div>
<div class="sect3">
<h4 id="_kafka">5.13.1. Kafka</h4>
<div class="paragraph">
<p>Kafka版本为0.11</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="pygments highlight"><code data-lang="xml"><span></span><span class="tok-nt">&lt;dependency&gt;</span>
  <span class="tok-nt">&lt;groupId&gt;</span>org.apache.flink<span class="tok-nt">&lt;/groupId&gt;</span>
  <span class="tok-nt">&lt;artifactId&gt;</span>flink-connector-kafka-0.11_2.11<span class="tok-nt">&lt;/artifactId&gt;</span>
  <span class="tok-nt">&lt;version&gt;</span>1.10.0<span class="tok-nt">&lt;/version&gt;</span>
<span class="tok-nt">&lt;/dependency&gt;</span></code></pre>
</div>
</div>
<div class="paragraph">
<p>Kafka版本为2.0以上</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="pygments highlight"><code data-lang="xml"><span></span><span class="tok-nt">&lt;dependency&gt;</span>
  <span class="tok-nt">&lt;groupId&gt;</span>org.apache.flink<span class="tok-nt">&lt;/groupId&gt;</span>
  <span class="tok-nt">&lt;artifactId&gt;</span>flink-connector-kafka_2.11<span class="tok-nt">&lt;/artifactId&gt;</span>
  <span class="tok-nt">&lt;version&gt;</span>1.10.0<span class="tok-nt">&lt;/version&gt;</span>
<span class="tok-nt">&lt;/dependency&gt;</span></code></pre>
</div>
</div>
<div class="paragraph">
<p>主函数中添加sink：</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="pygments highlight"><code data-lang="scala"><span></span><span class="tok-k">val</span> <span class="tok-n">union</span> <span class="tok-k">=</span> <span class="tok-n">high</span><span class="tok-o">.</span><span class="tok-n">union</span><span class="tok-o">(</span><span class="tok-n">low</span><span class="tok-o">).</span><span class="tok-n">map</span><span class="tok-o">(</span><span class="tok-k">_</span><span class="tok-o">.</span><span class="tok-n">temperature</span><span class="tok-o">.</span><span class="tok-n">toString</span><span class="tok-o">)</span>
<span class="tok-n">union</span><span class="tok-o">.</span><span class="tok-n">addSink</span><span class="tok-o">(</span><span class="tok-k">new</span> <span class="tok-nc">FlinkKafkaProducer011</span><span class="tok-o">[</span><span class="tok-kt">String</span><span class="tok-o">](</span><span class="tok-s">&quot;localhost:9092&quot;</span><span class="tok-o">,</span> <span class="tok-s">&quot;test&quot;</span><span class="tok-o">,</span> <span class="tok-k">new</span> <span class="tok-nc">SimpleStringSchema</span><span class="tok-o">()))</span></code></pre>
</div>
</div>
</div>
<div class="sect3">
<h4 id="_redis">5.13.2. Redis</h4>
<div class="listingblock">
<div class="content">
<pre class="pygments highlight"><code data-lang="xml"><span></span><span class="tok-nt">&lt;dependency&gt;</span>
  <span class="tok-nt">&lt;groupId&gt;</span>org.apache.bahir<span class="tok-nt">&lt;/groupId&gt;</span>
  <span class="tok-nt">&lt;artifactId&gt;</span>flink-connector-redis_2.11<span class="tok-nt">&lt;/artifactId&gt;</span>
  <span class="tok-nt">&lt;version&gt;</span>1.0<span class="tok-nt">&lt;/version&gt;</span>
<span class="tok-nt">&lt;/dependency&gt;</span></code></pre>
</div>
</div>
<div class="paragraph">
<p>定义一个redis的mapper类，用于定义保存到redis时调用的命令：</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="pygments highlight"><code data-lang="scala"><span></span><span class="tok-k">class</span> <span class="tok-nc">MyRedisMapper</span> <span class="tok-k">extends</span> <span class="tok-nc">RedisMapper</span><span class="tok-o">[</span><span class="tok-kt">SensorReading</span><span class="tok-o">]</span> <span class="tok-o">{</span>

  <span class="tok-k">override</span> <span class="tok-k">def</span> <span class="tok-n">getCommandDescription</span><span class="tok-k">:</span> <span class="tok-kt">RedisCommandDescription</span> <span class="tok-o">=</span> <span class="tok-o">{</span>
    <span class="tok-k">new</span> <span class="tok-nc">RedisCommandDescription</span><span class="tok-o">(</span><span class="tok-nc">RedisCommand</span><span class="tok-o">.</span><span class="tok-nc">HSET</span><span class="tok-o">,</span> <span class="tok-s">&quot;sensor_temperature&quot;</span><span class="tok-o">)</span>
  <span class="tok-o">}</span>

  <span class="tok-k">override</span> <span class="tok-k">def</span> <span class="tok-n">getValueFromData</span><span class="tok-o">(</span><span class="tok-n">t</span><span class="tok-k">:</span> <span class="tok-kt">SensorReading</span><span class="tok-o">)</span><span class="tok-k">:</span> <span class="tok-kt">String</span> <span class="tok-o">=</span> <span class="tok-n">t</span><span class="tok-o">.</span><span class="tok-n">temperature</span><span class="tok-o">.</span><span class="tok-n">toString</span>

  <span class="tok-k">override</span> <span class="tok-k">def</span> <span class="tok-n">getKeyFromData</span><span class="tok-o">(</span><span class="tok-n">t</span><span class="tok-k">:</span> <span class="tok-kt">SensorReading</span><span class="tok-o">)</span><span class="tok-k">:</span> <span class="tok-kt">String</span> <span class="tok-o">=</span> <span class="tok-n">t</span><span class="tok-o">.</span><span class="tok-n">id</span>

<span class="tok-o">}</span></code></pre>
</div>
</div>
</div>
<div class="sect3">
<h4 id="_elasticsearch">5.13.3. ElasticSearch</h4>
<div class="paragraph">
<p>在主函数中调用：</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="pygments highlight"><code data-lang="scala"><span></span><span class="tok-o">&lt;</span><span class="tok-n">dependency</span><span class="tok-o">&gt;</span>
  <span class="tok-o">&lt;</span><span class="tok-n">groupId</span><span class="tok-o">&gt;</span><span class="tok-n">org</span><span class="tok-o">.</span><span class="tok-n">apache</span><span class="tok-o">.</span><span class="tok-n">flink</span><span class="tok-o">&lt;/</span><span class="tok-n">groupId</span><span class="tok-o">&gt;</span>
  <span class="tok-o">&lt;</span><span class="tok-n">artifactId</span><span class="tok-o">&gt;</span><span class="tok-n">flink</span><span class="tok-o">-</span><span class="tok-n">connector</span><span class="tok-o">-</span><span class="tok-n">elasticsearch6_2</span><span class="tok-o">.</span><span class="tok-mi">11</span><span class="tok-o">&lt;/</span><span class="tok-n">artifactId</span><span class="tok-o">&gt;</span>
  <span class="tok-o">&lt;</span><span class="tok-n">version</span><span class="tok-o">&gt;</span><span class="tok-mf">1.10</span><span class="tok-o">.</span><span class="tok-mi">0</span><span class="tok-o">&lt;/</span><span class="tok-n">version</span><span class="tok-o">&gt;</span>
<span class="tok-o">&lt;/</span><span class="tok-n">dependency</span><span class="tok-o">&gt;</span></code></pre>
</div>
</div>
<div class="paragraph">
<p>在主函数中调用：</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="pygments highlight"><code data-lang="scala"><span></span><span class="tok-k">val</span> <span class="tok-n">httpHosts</span> <span class="tok-k">=</span> <span class="tok-k">new</span> <span class="tok-n">util</span><span class="tok-o">.</span><span class="tok-nc">ArrayList</span><span class="tok-o">[</span><span class="tok-kt">HttpHost</span><span class="tok-o">]()</span>
<span class="tok-n">httpHosts</span><span class="tok-o">.</span><span class="tok-n">add</span><span class="tok-o">(</span><span class="tok-k">new</span> <span class="tok-nc">HttpHost</span><span class="tok-o">(</span><span class="tok-s">&quot;localhost&quot;</span><span class="tok-o">,</span> <span class="tok-mi">9200</span><span class="tok-o">))</span>
<span class="tok-k">val</span> <span class="tok-n">esSinkBuilder</span> <span class="tok-k">=</span> <span class="tok-k">new</span> <span class="tok-nc">ElasticsearchSink</span><span class="tok-o">.</span><span class="tok-nc">Builder</span><span class="tok-o">[</span><span class="tok-kt">SensorReading</span><span class="tok-o">](</span>
  <span class="tok-n">httpHosts</span><span class="tok-o">,</span>
  <span class="tok-k">new</span> <span class="tok-nc">ElasticsearchSinkFunction</span><span class="tok-o">[</span><span class="tok-kt">SensorReading</span><span class="tok-o">]</span> <span class="tok-o">{</span>
    <span class="tok-k">override</span> <span class="tok-k">def</span> <span class="tok-n">process</span><span class="tok-o">(</span><span class="tok-n">t</span><span class="tok-k">:</span> <span class="tok-kt">SensorReading</span><span class="tok-o">,</span> <span class="tok-n">runtimeContext</span><span class="tok-k">:</span> <span class="tok-kt">RuntimeContext</span><span class="tok-o">,</span> <span class="tok-n">requestIndexer</span><span class="tok-k">:</span> <span class="tok-kt">RequestIndexer</span><span class="tok-o">)</span><span class="tok-k">:</span> <span class="tok-kt">Unit</span> <span class="tok-o">=</span> <span class="tok-o">{</span>
      <span class="tok-n">println</span><span class="tok-o">(</span><span class="tok-s">&quot;saving data: &quot;</span> <span class="tok-o">+</span> <span class="tok-n">t</span><span class="tok-o">)</span>
      <span class="tok-k">val</span> <span class="tok-n">json</span> <span class="tok-k">=</span> <span class="tok-k">new</span> <span class="tok-n">util</span><span class="tok-o">.</span><span class="tok-nc">HashMap</span><span class="tok-o">[</span><span class="tok-kt">String</span>, <span class="tok-kt">String</span><span class="tok-o">]()</span>
      <span class="tok-n">json</span><span class="tok-o">.</span><span class="tok-n">put</span><span class="tok-o">(</span><span class="tok-s">&quot;data&quot;</span><span class="tok-o">,</span> <span class="tok-n">t</span><span class="tok-o">.</span><span class="tok-n">toString</span><span class="tok-o">)</span>
      <span class="tok-k">val</span> <span class="tok-n">indexRequest</span> <span class="tok-k">=</span> <span class="tok-nc">Requests</span>
        <span class="tok-o">.</span><span class="tok-n">indexRequest</span><span class="tok-o">()</span>
        <span class="tok-o">.</span><span class="tok-n">index</span><span class="tok-o">(</span><span class="tok-s">&quot;sensor&quot;</span><span class="tok-o">)</span>
        <span class="tok-o">.</span><span class="tok-n">`type`</span><span class="tok-o">(</span><span class="tok-s">&quot;readingData&quot;</span><span class="tok-o">)</span>
        <span class="tok-o">.</span><span class="tok-n">source</span><span class="tok-o">(</span><span class="tok-n">json</span><span class="tok-o">)</span>
      <span class="tok-n">requestIndexer</span><span class="tok-o">.</span><span class="tok-n">add</span><span class="tok-o">(</span><span class="tok-n">indexRequest</span><span class="tok-o">)</span>
      <span class="tok-n">println</span><span class="tok-o">(</span><span class="tok-s">&quot;saved successfully&quot;</span><span class="tok-o">)</span>
    <span class="tok-o">}</span>
  <span class="tok-o">})</span>
<span class="tok-n">dataStream</span><span class="tok-o">.</span><span class="tok-n">addSink</span><span class="tok-o">(</span><span class="tok-n">esSinkBuilder</span><span class="tok-o">.</span><span class="tok-n">build</span><span class="tok-o">())</span></code></pre>
</div>
</div>
</div>
<div class="sect3">
<h4 id="_jdbc自定义sink">5.13.4. JDBC自定义sink</h4>
<div class="listingblock">
<div class="content">
<pre class="pygments highlight"><code data-lang="xml"><span></span><span class="tok-nt">&lt;dependency&gt;</span>
  <span class="tok-nt">&lt;groupId&gt;</span>mysql<span class="tok-nt">&lt;/groupId&gt;</span>
  <span class="tok-nt">&lt;artifactId&gt;</span>mysql-connector-java<span class="tok-nt">&lt;/artifactId&gt;</span>
  <span class="tok-nt">&lt;version&gt;</span>5.1.44<span class="tok-nt">&lt;/version&gt;</span>
<span class="tok-nt">&lt;/dependency&gt;</span></code></pre>
</div>
</div>
<div class="paragraph">
<p>添加MyJdbcSink</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="pygments highlight"><code data-lang="scala"><span></span><span class="tok-k">class</span> <span class="tok-nc">MyJdbcSink</span><span class="tok-o">()</span> <span class="tok-k">extends</span> <span class="tok-nc">RichSinkFunction</span><span class="tok-o">[</span><span class="tok-kt">SensorReading</span><span class="tok-o">]{</span>
  <span class="tok-k">var</span> <span class="tok-n">conn</span><span class="tok-k">:</span> <span class="tok-kt">Connection</span> <span class="tok-o">=</span> <span class="tok-k">_</span>
  <span class="tok-k">var</span> <span class="tok-n">insertStmt</span><span class="tok-k">:</span> <span class="tok-kt">PreparedStatement</span> <span class="tok-o">=</span> <span class="tok-k">_</span>
  <span class="tok-k">var</span> <span class="tok-n">updateStmt</span><span class="tok-k">:</span> <span class="tok-kt">PreparedStatement</span> <span class="tok-o">=</span> <span class="tok-k">_</span>
  <span class="tok-c1">// open 主要是创建连接</span>
  <span class="tok-k">override</span> <span class="tok-k">def</span> <span class="tok-n">open</span><span class="tok-o">(</span><span class="tok-n">parameters</span><span class="tok-k">:</span> <span class="tok-kt">Configuration</span><span class="tok-o">)</span><span class="tok-k">:</span> <span class="tok-kt">Unit</span> <span class="tok-o">=</span> <span class="tok-o">{</span>
    <span class="tok-k">super</span><span class="tok-o">.</span><span class="tok-n">open</span><span class="tok-o">(</span><span class="tok-n">parameters</span><span class="tok-o">)</span>
    <span class="tok-n">conn</span> <span class="tok-k">=</span> <span class="tok-nc">DriverManager</span><span class="tok-o">.</span><span class="tok-n">getConnection</span><span class="tok-o">(</span><span class="tok-s">&quot;jdbc:mysql://localhost:3306/test&quot;</span><span class="tok-o">,</span> <span class="tok-s">&quot;root&quot;</span><span class="tok-o">,</span> <span class="tok-s">&quot;123456&quot;</span><span class="tok-o">)</span>
    <span class="tok-n">insertStmt</span> <span class="tok-k">=</span> <span class="tok-n">conn</span><span class="tok-o">.</span><span class="tok-n">prepareStatement</span><span class="tok-o">(</span><span class="tok-s">&quot;INSERT INTO temperatures (sensor, temp) VALUES (?, ?)&quot;</span><span class="tok-o">)</span>
    <span class="tok-n">updateStmt</span> <span class="tok-k">=</span> <span class="tok-n">conn</span><span class="tok-o">.</span><span class="tok-n">prepareStatement</span><span class="tok-o">(</span><span class="tok-s">&quot;UPDATE temperatures SET temp = ? WHERE sensor = ?&quot;</span><span class="tok-o">)</span>
  <span class="tok-o">}</span>
  <span class="tok-c1">// 调用连接，执行sql</span>
  <span class="tok-k">override</span> <span class="tok-k">def</span> <span class="tok-n">invoke</span><span class="tok-o">(</span><span class="tok-n">value</span><span class="tok-k">:</span> <span class="tok-kt">SensorReading</span><span class="tok-o">,</span> <span class="tok-n">context</span><span class="tok-k">:</span> <span class="tok-kt">SinkFunction.Context</span><span class="tok-o">[</span><span class="tok-k">_</span><span class="tok-o">])</span><span class="tok-k">:</span> <span class="tok-kt">Unit</span> <span class="tok-o">=</span> <span class="tok-o">{</span>
    <span class="tok-n">updateStmt</span><span class="tok-o">.</span><span class="tok-n">setDouble</span><span class="tok-o">(</span><span class="tok-mi">1</span><span class="tok-o">,</span> <span class="tok-n">value</span><span class="tok-o">.</span><span class="tok-n">temperature</span><span class="tok-o">)</span>
    <span class="tok-n">updateStmt</span><span class="tok-o">.</span><span class="tok-n">setString</span><span class="tok-o">(</span><span class="tok-mi">2</span><span class="tok-o">,</span> <span class="tok-n">value</span><span class="tok-o">.</span><span class="tok-n">id</span><span class="tok-o">)</span>
    <span class="tok-n">updateStmt</span><span class="tok-o">.</span><span class="tok-n">execute</span><span class="tok-o">()</span>

    <span class="tok-k">if</span> <span class="tok-o">(</span><span class="tok-n">updateStmt</span><span class="tok-o">.</span><span class="tok-n">getUpdateCount</span> <span class="tok-o">==</span> <span class="tok-mi">0</span><span class="tok-o">)</span> <span class="tok-o">{</span>
      <span class="tok-n">insertStmt</span><span class="tok-o">.</span><span class="tok-n">setString</span><span class="tok-o">(</span><span class="tok-mi">1</span><span class="tok-o">,</span> <span class="tok-n">value</span><span class="tok-o">.</span><span class="tok-n">id</span><span class="tok-o">)</span>
      <span class="tok-n">insertStmt</span><span class="tok-o">.</span><span class="tok-n">setDouble</span><span class="tok-o">(</span><span class="tok-mi">2</span><span class="tok-o">,</span> <span class="tok-n">value</span><span class="tok-o">.</span><span class="tok-n">temperature</span><span class="tok-o">)</span>
      <span class="tok-n">insertStmt</span><span class="tok-o">.</span><span class="tok-n">execute</span><span class="tok-o">()</span>
    <span class="tok-o">}</span>
  <span class="tok-o">}</span>

  <span class="tok-k">override</span> <span class="tok-k">def</span> <span class="tok-n">close</span><span class="tok-o">()</span><span class="tok-k">:</span> <span class="tok-kt">Unit</span> <span class="tok-o">=</span> <span class="tok-o">{</span>
    <span class="tok-n">insertStmt</span><span class="tok-o">.</span><span class="tok-n">close</span><span class="tok-o">()</span>
    <span class="tok-n">updateStmt</span><span class="tok-o">.</span><span class="tok-n">close</span><span class="tok-o">()</span>
    <span class="tok-n">conn</span><span class="tok-o">.</span><span class="tok-n">close</span><span class="tok-o">()</span>
  <span class="tok-o">}</span>
<span class="tok-o">}</span></code></pre>
</div>
</div>
<div class="paragraph">
<p>在main方法中增加，把明细保存到mysql中</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="pygments highlight"><code data-lang="scala"><span></span><span class="tok-n">dataStream</span><span class="tok-o">.</span><span class="tok-n">addSink</span><span class="tok-o">(</span><span class="tok-k">new</span> <span class="tok-nc">MyJdbcSink</span><span class="tok-o">())</span></code></pre>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="sect1">
<h2 id="_基于时间和窗口的操作符">6. 基于时间和窗口的操作符</h2>
<div class="sectionbody">
<div class="paragraph">
<p>在本章，我们将要学习DataStream API中处理时间和基于时间的操作符，例如窗口操作符。</p>
</div>
<div class="paragraph">
<p>首先，我们会学习如何定义时间属性，时间戳和水位线。然后我们将会学习底层操作process function，它可以让我们访问时间戳和水位线，以及注册定时器事件。接下来，我们将会使用Flink的window API，它提供了通常使用的各种窗口类型的内置实现。我们将会学到如何进行用户自定义窗口操作符，以及窗口的核心功能：assigners（分配器）、triggers（触发器）和evictors（清理器）。最后，我们将讨论如何基于时间来做流的联结查询，以及处理迟到事件的策略。</p>
</div>
<div class="sect2">
<h3 id="_设置时间属性">6.1. 设置时间属性</h3>
<div class="paragraph">
<p>如果我们想要在分布式流处理应用程序中定义有关时间的操作，彻底理解时间的语义是非常重要的。当我们指定了一个窗口去收集某1分钟内的数据时，这个长度为1分钟的桶中，到底应该包含哪些数据？在DataStream API中，我们将使用时间属性来告诉Flink：当我们创建窗口时，我们如何定义时间。时间属性是<code>StreamExecutionEnvironment</code>的一个属性，有以下值：</p>
</div>
<div class="paragraph">
<p><strong>ProcessingTime</strong></p>
</div>
<div class="admonitionblock note">
<table>
<tr>
<td class="icon">
<i class="fa icon-note" title="Note"></i>
</td>
<td class="content">
机器时间在分布式系统中又叫做“墙上时钟”。
</td>
</tr>
</table>
</div>
<div class="paragraph">
<p>当操作符执行时，此操作符看到的时间是操作符所在机器的机器时间。Processing-time window的触发取决于机器时间，窗口包含的元素也是那个机器时间段内到达的元素。通常情况下，窗口操作符使用processing time会导致不确定的结果，因为基于机器时间的窗口中收集的元素取决于元素到达的速度快慢。使用processing time会为程序提供极低的延迟，因为无需等待水位线的到达。</p>
</div>
<div class="admonitionblock note">
<table>
<tr>
<td class="icon">
<i class="fa icon-note" title="Note"></i>
</td>
<td class="content">
如果要追求极限的低延迟，请使用processing time。
</td>
</tr>
</table>
</div>
<div class="paragraph">
<p><strong>EventTime</strong></p>
</div>
<div class="paragraph">
<p>当操作符执行时，操作符看的当前时间是由流中元素所携带的信息决定的。流中的每一个元素都必须包含时间戳信息。而系统的逻辑时钟由水位线(Watermark)定义。我们之前学习过，时间戳要么在事件进入流处理程序之前已经存在，要么就需要在程序的数据源（source）处进行分配。当水位线宣布特定时间段的数据都已经到达，事件时间窗口将会被触发计算。即使数据到达的顺序是乱序的，事件时间窗口的计算结果也将是确定性的。窗口的计算结果并不取决于元素到达的快与慢。</p>
</div>
<div class="admonitionblock note">
<table>
<tr>
<td class="icon">
<i class="fa icon-note" title="Note"></i>
</td>
<td class="content">
当水位线超过事件时间窗口的结束时间时，窗口将会闭合，不再接收数据，并触发计算。
</td>
</tr>
</table>
</div>
<div class="paragraph">
<p><strong>IngestionTime</strong></p>
</div>
<div class="paragraph">
<p>当事件进入source操作符时，source操作符所在机器的机器时间，就是此事件的“摄入时间”（IngestionTime），并同时产生水位线。IngestionTime相当于EventTime和ProcessingTime的混合体。一个事件的IngestionTime其实就是它进入流处理器中的时间。</p>
</div>
<div class="admonitionblock note">
<table>
<tr>
<td class="icon">
<i class="fa icon-note" title="Note"></i>
</td>
<td class="content">
IngestionTime没什么价值，既有EventTime的执行效率（比较低），有没有EventTime计算结果的准确性。
</td>
</tr>
</table>
</div>
<div class="paragraph">
<p>下面的例子展示了如何设置事件时间。</p>
</div>
<div class="listingblock">
<div class="title">Example6_1.scala</div>
<div class="content">
<pre class="pygments highlight"><code data-lang="scala"><span></span><span class="tok-k">object</span> <span class="tok-nc">AverageSensorReadings</span> <span class="tok-o">{</span>
  <span class="tok-k">def</span> <span class="tok-n">main</span><span class="tok-o">(</span><span class="tok-n">args</span><span class="tok-k">:</span> <span class="tok-kt">Array</span><span class="tok-o">[</span><span class="tok-kt">String</span><span class="tok-o">])</span> <span class="tok-o">{</span>
    <span class="tok-k">val</span> <span class="tok-n">env</span> <span class="tok-k">=</span> <span class="tok-nc">StreamExecutionEnvironment</span><span class="tok-o">.</span><span class="tok-n">getExecutionEnvironment</span>
    <span class="tok-n">env</span><span class="tok-o">.</span><span class="tok-n">setStreamTimeCharacteristic</span><span class="tok-o">(</span><span class="tok-nc">TimeCharacteristic</span><span class="tok-o">.</span><span class="tok-nc">EventTime</span><span class="tok-o">)</span>
    <span class="tok-k">val</span> <span class="tok-n">sensorData</span><span class="tok-k">:</span> <span class="tok-kt">DataStream</span><span class="tok-o">[</span><span class="tok-kt">SensorReading</span><span class="tok-o">]</span> <span class="tok-k">=</span> <span class="tok-n">env</span><span class="tok-o">.</span><span class="tok-n">addSource</span><span class="tok-o">(...)</span>
  <span class="tok-o">}</span>
<span class="tok-o">}</span></code></pre>
</div>
</div>
<div class="paragraph">
<p>如果要使用processing time，将<code>TimeCharacteristic.EventTime</code>替换为<code>TimeCharacteristic.ProcessingTIme</code>就可以了。</p>
</div>
<div class="sect3">
<h4 id="_指定时间戳和产生水位线">6.1.1. 指定时间戳和产生水位线</h4>
<div class="paragraph">
<p>如果使用事件时间，那么流中的事件必须包含这个事件真正发生的时间。使用了事件时间的流必须携带水位线。</p>
</div>
<div class="paragraph">
<p>时间戳和水位线的单位是毫秒，记时从<code>1970-01-01T00:00:00Z</code>开始。到达某个操作符的水位线就会告知这个操作符：小于等于水位线中携带的时间戳的事件都已经到达这个操作符了。时间戳和水位线可以由<code>SourceFunction</code>产生，或者由用户自定义的时间戳分配器和水位线产生器来生成。</p>
</div>
<div class="paragraph">
<p>Flink暴露了TimestampAssigner接口供我们实现，使我们可以自定义如何从事件数据中抽取时间戳。一般来说，时间戳分配器需要在source操作符后马上进行调用。</p>
</div>
<div class="admonitionblock note">
<table>
<tr>
<td class="icon">
<i class="fa icon-note" title="Note"></i>
</td>
<td class="content">
因为时间戳分配器看到的元素的顺序应该和source操作符产生数据的顺序是一样的，否则就乱了。这就是为什么我们经常将source操作符的并行度设置为1的原因。
</td>
</tr>
</table>
</div>
<div class="paragraph">
<p>也就是说，任何分区操作都会将元素的顺序打乱，例如：并行度改变，keyBy()操作等等。</p>
</div>
<div class="paragraph">
<p>所以最佳实践是：在尽量接近数据源source操作符的地方分配时间戳和产生水位线，甚至最好在SourceFunction中分配时间戳和产生水位线。当然在分配时间戳和产生水位线之前可以对流进行map和filter操作是没问题的，也就是说必须是窄依赖。</p>
</div>
<div class="paragraph">
<p>以下这种写法是可以的。</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="pygments highlight"><code data-lang="scala"><span></span><span class="tok-k">val</span> <span class="tok-n">stream</span> <span class="tok-k">=</span> <span class="tok-n">env</span>
  <span class="tok-o">.</span><span class="tok-n">addSource</span><span class="tok-o">(...)</span>
  <span class="tok-o">.</span><span class="tok-n">map</span><span class="tok-o">(...)</span>
  <span class="tok-o">.</span><span class="tok-n">filter</span><span class="tok-o">(...)</span>
  <span class="tok-o">.</span><span class="tok-n">assignTimestampsAndWatermarks</span><span class="tok-o">(...)</span></code></pre>
</div>
</div>
<div class="paragraph">
<p>下面的例子展示了首先filter流，然后再分配时间戳和水位线。</p>
</div>
<div class="listingblock">
<div class="title">Example6_2.scala</div>
<div class="content">
<pre class="pygments highlight"><code data-lang="scala"><span></span><span class="tok-k">val</span> <span class="tok-n">env</span> <span class="tok-k">=</span> <span class="tok-nc">StreamExecutionEnvironment</span><span class="tok-o">.</span><span class="tok-n">getExecutionEnvironment</span>

<span class="tok-c1">// 从调用时刻开始给env创建的每一个stream追加时间特征</span>
<span class="tok-n">env</span><span class="tok-o">.</span><span class="tok-n">setStreamTimeCharacteristic</span><span class="tok-o">(</span><span class="tok-nc">TimeCharacteristic</span><span class="tok-o">.</span><span class="tok-nc">EventTime</span><span class="tok-o">)</span>

<span class="tok-k">val</span> <span class="tok-n">readings</span><span class="tok-k">:</span> <span class="tok-kt">DataStream</span><span class="tok-o">[</span><span class="tok-kt">SensorReading</span><span class="tok-o">]</span> <span class="tok-k">=</span> <span class="tok-n">env</span>
  <span class="tok-o">.</span><span class="tok-n">addSource</span><span class="tok-o">(</span><span class="tok-k">new</span> <span class="tok-nc">SensorSource</span><span class="tok-o">)</span>
  <span class="tok-o">.</span><span class="tok-n">filter</span><span class="tok-o">(</span><span class="tok-n">r</span> <span class="tok-k">=&gt;</span> <span class="tok-n">r</span><span class="tok-o">.</span><span class="tok-n">temperature</span> <span class="tok-o">&gt;</span> <span class="tok-mi">25</span><span class="tok-o">)</span>
  <span class="tok-o">.</span><span class="tok-n">assignTimestampsAndWatermarks</span><span class="tok-o">(</span><span class="tok-k">new</span> <span class="tok-nc">MyAssigner</span><span class="tok-o">())</span></code></pre>
</div>
</div>
<div class="paragraph">
<p>MyAssigner有两种类型</p>
</div>
<div class="ulist">
<ul>
<li>
<p>AssignerWithPeriodicWatermarks</p>
</li>
<li>
<p>AssignerWithPunctuatedWatermarks</p>
</li>
</ul>
</div>
<div class="paragraph">
<p>以上两个接口都继承自TimestampAssigner。</p>
</div>
</div>
<div class="sect3">
<h4 id="_周期性的生成水位线">6.1.2. 周期性的生成水位线</h4>
<div class="paragraph">
<p>周期性的生成水位线：系统会周期性的将水位线插入到流中（水位线也是一种特殊的事件!）。默认周期是200毫秒，也就是说，系统会每隔200毫秒就往流中插入一次水位线。</p>
</div>
<div class="admonitionblock note">
<table>
<tr>
<td class="icon">
<i class="fa icon-note" title="Note"></i>
</td>
<td class="content">
这里的200毫秒是机器时间！
</td>
</tr>
</table>
</div>
<div class="paragraph">
<p>可以使用<code>ExecutionConfig.setAutoWatermarkInterval()</code>方法进行设置。</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="pygments highlight"><code data-lang="scala"><span></span><span class="tok-k">val</span> <span class="tok-n">env</span> <span class="tok-k">=</span> <span class="tok-nc">StreamExecutionEnvironment</span><span class="tok-o">.</span><span class="tok-n">getExecutionEnvironment</span>
<span class="tok-n">env</span><span class="tok-o">.</span><span class="tok-n">setStreamTimeCharacteristic</span><span class="tok-o">(</span><span class="tok-nc">TimeCharacteristic</span><span class="tok-o">.</span><span class="tok-nc">EventTime</span><span class="tok-o">)</span>
<span class="tok-c1">// 每隔5秒产生一个水位线</span>
<span class="tok-n">env</span><span class="tok-o">.</span><span class="tok-n">getConfig</span><span class="tok-o">.</span><span class="tok-n">setAutoWatermarkInterval</span><span class="tok-o">(</span><span class="tok-mi">5000</span><span class="tok-o">)</span></code></pre>
</div>
</div>
<div class="paragraph">
<p>上面的例子产生水位线的逻辑：每隔5秒钟，Flink会调用AssignerWithPeriodicWatermarks中的getCurrentWatermark()方法。如果方法返回的时间戳大于之前水位线的时间戳，新的水位线会被插入到流中。这个检查保证了水位线是单调递增的。如果方法返回的时间戳小于等于之前水位线的时间戳，则不会产生新的水位线。</p>
</div>
<div class="paragraph">
<p>例子，自定义一个周期性的时间戳抽取</p>
</div>
<div class="listingblock">
<div class="title">Example6_3.scala</div>
<div class="content">
<pre class="pygments highlight"><code data-lang="scala"><span></span><span class="tok-k">class</span> <span class="tok-nc">PeriodicAssigner</span> <span class="tok-k">extends</span> <span class="tok-nc">AssignerWithPeriodicWatermarks</span><span class="tok-o">[</span><span class="tok-kt">SensorReading</span><span class="tok-o">]</span> <span class="tok-o">{</span>
  <span class="tok-k">val</span> <span class="tok-n">bound</span><span class="tok-k">:</span> <span class="tok-kt">Long</span> <span class="tok-o">=</span> <span class="tok-mi">60</span> <span class="tok-o">*</span> <span class="tok-mi">1000</span> <span class="tok-c1">// 延时为1分钟</span>
  <span class="tok-k">var</span> <span class="tok-n">maxTs</span><span class="tok-k">:</span> <span class="tok-kt">Long</span> <span class="tok-o">=</span> <span class="tok-nc">Long</span><span class="tok-o">.</span><span class="tok-nc">MinValue</span> <span class="tok-o">+</span> <span class="tok-n">bound</span> <span class="tok-c1">// 观察到的最大时间戳</span>

  <span class="tok-k">override</span> <span class="tok-k">def</span> <span class="tok-n">getCurrentWatermark</span><span class="tok-k">:</span> <span class="tok-kt">Watermark</span> <span class="tok-o">=</span> <span class="tok-o">{</span>
    <span class="tok-k">new</span> <span class="tok-nc">Watermark</span><span class="tok-o">(</span><span class="tok-n">maxTs</span> <span class="tok-o">-</span> <span class="tok-n">bound</span><span class="tok-o">)</span>
  <span class="tok-o">}</span>

  <span class="tok-k">override</span> <span class="tok-k">def</span> <span class="tok-n">extractTimestamp</span><span class="tok-o">(</span><span class="tok-n">r</span><span class="tok-k">:</span> <span class="tok-kt">SensorReading</span><span class="tok-o">,</span> <span class="tok-n">previousTS</span><span class="tok-k">:</span> <span class="tok-kt">Long</span><span class="tok-o">)</span> <span class="tok-k">=</span> <span class="tok-o">{</span>
    <span class="tok-n">maxTs</span> <span class="tok-k">=</span> <span class="tok-n">maxTs</span><span class="tok-o">.</span><span class="tok-n">max</span><span class="tok-o">(</span><span class="tok-n">r</span><span class="tok-o">.</span><span class="tok-n">timestamp</span><span class="tok-o">)</span>
    <span class="tok-n">r</span><span class="tok-o">.</span><span class="tok-n">timestamp</span>
  <span class="tok-o">}</span>
<span class="tok-o">}</span></code></pre>
</div>
</div>
<div class="paragraph">
<p>如果我们事先得知数据流的时间戳是单调递增的，也就是说没有乱序。我们可以使用assignAscendingTimestamps，方法会直接使用数据的时间戳生成水位线。</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="pygments highlight"><code data-lang="scala"><span></span><span class="tok-k">val</span> <span class="tok-n">stream</span><span class="tok-k">:</span> <span class="tok-kt">DataStream</span><span class="tok-o">[</span><span class="tok-kt">SensorReading</span><span class="tok-o">]</span> <span class="tok-k">=</span> <span class="tok-o">...</span>
<span class="tok-k">val</span> <span class="tok-n">withTimestampsAndWatermarks</span> <span class="tok-k">=</span> <span class="tok-n">stream</span>
  <span class="tok-o">.</span><span class="tok-n">assignAscendingTimestamps</span><span class="tok-o">(</span><span class="tok-n">e</span> <span class="tok-k">=&gt;</span> <span class="tok-n">e</span><span class="tok-o">.</span><span class="tok-n">timestamp</span><span class="tok-o">)</span></code></pre>
</div>
</div>
<div class="paragraph">
<p>如果我们能大致估算出数据流中的事件的最大延迟时间，可以使用如下代码：</p>
</div>
<div class="admonitionblock note">
<table>
<tr>
<td class="icon">
<i class="fa icon-note" title="Note"></i>
</td>
<td class="content">
最大延迟时间就是当前到达的事件的事件时间和之前所有到达的事件中最大时间戳的差。
</td>
</tr>
</table>
</div>
<div class="listingblock">
<div class="content">
<pre class="pygments highlight"><code data-lang="scala"><span></span><span class="tok-k">val</span> <span class="tok-n">stream</span><span class="tok-k">:</span> <span class="tok-kt">DataStream</span><span class="tok-o">[</span><span class="tok-kt">SensorReading</span><span class="tok-o">]</span> <span class="tok-k">=</span> <span class="tok-o">...</span>
<span class="tok-k">val</span> <span class="tok-n">withTimestampsAndWatermarks</span> <span class="tok-k">=</span> <span class="tok-n">stream</span><span class="tok-o">.</span><span class="tok-n">assignTimestampsAndWatermarks</span><span class="tok-o">(</span>
  <span class="tok-k">new</span> <span class="tok-nc">SensorTimeAssigner</span>
<span class="tok-o">)</span>

<span class="tok-k">class</span> <span class="tok-nc">SensorTimeAssigner</span>
  <span class="tok-k">extends</span> <span class="tok-nc">BoundedOutOfOrdernessTimestampExtractor</span><span class="tok-o">[</span><span class="tok-kt">SensorReading</span><span class="tok-o">](</span><span class="tok-nc">Time</span><span class="tok-o">.</span><span class="tok-n">seconds</span><span class="tok-o">(</span><span class="tok-mi">5</span><span class="tok-o">))</span> <span class="tok-o">{</span>

  <span class="tok-c1">// 抽取时间戳</span>
  <span class="tok-k">override</span> <span class="tok-k">def</span> <span class="tok-n">extractTimestamp</span><span class="tok-o">(</span><span class="tok-n">r</span><span class="tok-k">:</span> <span class="tok-kt">SensorReading</span><span class="tok-o">)</span><span class="tok-k">:</span> <span class="tok-kt">Long</span> <span class="tok-o">=</span> <span class="tok-n">r</span><span class="tok-o">.</span><span class="tok-n">timestamp</span>
<span class="tok-o">}</span></code></pre>
</div>
</div>
<div class="paragraph">
<p>以上代码设置了最大延迟时间为5秒。</p>
</div>
</div>
<div class="sect3">
<h4 id="_如何产生不规则的水位线">6.1.3. 如何产生不规则的水位线</h4>
<div class="paragraph">
<p>直接上代码，只给sensor_1的传感器的数据流插入水位线</p>
</div>
<div class="listingblock">
<div class="title">Example6_4.scala</div>
<div class="content">
<pre class="pygments highlight"><code data-lang="scala"><span></span><span class="tok-k">class</span> <span class="tok-nc">PunctuatedAssigner</span> <span class="tok-k">extends</span> <span class="tok-nc">AssignerWithPunctuatedWatermarks</span><span class="tok-o">[</span><span class="tok-kt">SensorReading</span><span class="tok-o">]</span> <span class="tok-o">{</span>
  <span class="tok-k">val</span> <span class="tok-n">bound</span><span class="tok-k">:</span> <span class="tok-kt">Long</span> <span class="tok-o">=</span> <span class="tok-mi">60</span> <span class="tok-o">*</span> <span class="tok-mi">1000</span>

  <span class="tok-k">override</span> <span class="tok-k">def</span> <span class="tok-n">checkAndGetNextWatermark</span><span class="tok-o">(</span><span class="tok-n">r</span><span class="tok-k">:</span> <span class="tok-kt">SensorReading</span><span class="tok-o">,</span> <span class="tok-n">extractedTS</span><span class="tok-k">:</span> <span class="tok-kt">Long</span><span class="tok-o">)</span><span class="tok-k">:</span> <span class="tok-kt">Watermark</span> <span class="tok-o">=</span> <span class="tok-o">{</span>
    <span class="tok-k">if</span> <span class="tok-o">(</span><span class="tok-n">r</span><span class="tok-o">.</span><span class="tok-n">id</span> <span class="tok-o">==</span> <span class="tok-s">&quot;sensor_1&quot;</span><span class="tok-o">)</span> <span class="tok-o">{</span>
      <span class="tok-k">new</span> <span class="tok-nc">Watermark</span><span class="tok-o">(</span><span class="tok-n">extractedTS</span> <span class="tok-o">-</span> <span class="tok-n">bound</span><span class="tok-o">)</span>
    <span class="tok-o">}</span> <span class="tok-k">else</span> <span class="tok-o">{</span>
      <span class="tok-kc">null</span>
    <span class="tok-o">}</span>
  <span class="tok-o">}</span>

  <span class="tok-k">override</span> <span class="tok-k">def</span> <span class="tok-n">extractTimestamp</span><span class="tok-o">(</span><span class="tok-n">r</span><span class="tok-k">:</span> <span class="tok-kt">SensorReading</span><span class="tok-o">,</span> <span class="tok-n">previousTS</span><span class="tok-k">:</span> <span class="tok-kt">Long</span><span class="tok-o">)</span><span class="tok-k">:</span> <span class="tok-kt">Long</span> <span class="tok-o">=</span> <span class="tok-o">{</span>
    <span class="tok-n">r</span><span class="tok-o">.</span><span class="tok-n">timestamp</span>
  <span class="tok-o">}</span>
<span class="tok-o">}</span></code></pre>
</div>
</div>
<div class="paragraph">
<p>现在我们已经知道如何使用<code>TimestampAssigner</code>来产生水位线了。现在我们要讨论一下水位线会对我们的程序产生什么样的影响。</p>
</div>
<div class="paragraph">
<p>水位线用来平衡延迟和计算结果的正确性。水位线告诉我们，在触发计算（例如关闭窗口并触发窗口计算）之前，我们需要等待事件多长时间。基于事件时间的操作符根据水位线来衡量系统的逻辑时间的进度。</p>
</div>
<div class="paragraph">
<p>完美的水位线永远不会错：时间戳小于水位线的事件不会再出现。在特殊情况下(例如非乱序事件流)，最近一次事件的时间戳就可能是完美的水位线。启发式水位线则相反，它只估计时间，因此有可能出错，即迟到的事件(其时间戳小于水位线标记时间)晚于水位线出现。针对启发式水位线，Flink提供了处理迟到元素的机制。</p>
</div>
<div class="paragraph">
<p>设定水位线通常需要用到领域知识。举例来说，如果知道事件的迟到时间不会超过5秒，就可以将水位线标记时间设为收到的最大时间戳减去5秒。另一种做法是，采用一个Flink作业监控事件流，学习事件的迟到规律，并以此构建水位线生成模型。</p>
</div>
<div class="paragraph">
<p>如果最大延迟时间设置的很大，计算出的结果会更精确，但收到计算结果的速度会很慢，同时系统会缓存大量的数据，并对系统造成比较大的压力。如果最大延迟时间设置的很小，那么收到计算结果的速度会很快，但可能收到错误的计算结果。不过Flink处理迟到数据的机制可以解决这个问题。上述问题看起来很复杂，但是恰恰符合现实世界的规律：大部分真实的事件流都是乱序的，并且通常无法了解它们的乱序程度(因为理论上不能预见未来)。水位线是唯一让我们直面乱序事件流并保证正确性的机制; 否则只能选择忽视事实，假装错误的结果是正确的。</p>
</div>
</div>
</div>
<div class="sect2">
<h3 id="_process_functionlow_level_api">6.2. Process Function(Low-Level API)</h3>
<div class="paragraph">
<p>我们之前学习的转换算子是无法访问事件的时间戳信息和水位线信息的。而这在一些应用场景下，极为重要。例如MapFunction这样的map转换算子就无法访问时间戳或者当前事件的事件时间。</p>
</div>
<div class="paragraph">
<p>基于此，DataStream API提供了一系列的Low-Level转换算子。可以访问时间戳、水位线以及注册定时事件。还可以输出特定的一些事件，例如超时事件等。Process Function用来构建事件驱动的应用以及实现自定义的业务逻辑(使用之前的window函数和转换算子无法实现)。例如，Flink-SQL就是使用Process Function实现的。</p>
</div>
<div class="paragraph">
<p>Flink提供了8个Process Function：</p>
</div>
<div class="ulist">
<ul>
<li>
<p>ProcessFunction</p>
</li>
<li>
<p>KeyedProcessFunction</p>
</li>
<li>
<p>CoProcessFunction</p>
</li>
<li>
<p>ProcessJoinFunction</p>
</li>
<li>
<p>BroadcastProcessFunction</p>
</li>
<li>
<p>KeyedBroadcastProcessFunction</p>
</li>
<li>
<p>ProcessWindowFunction</p>
</li>
<li>
<p>ProcessAllWindowFunction</p>
</li>
</ul>
</div>
<div class="paragraph">
<p>我们这里详细介绍一下KeyedProcessFunction。</p>
</div>
<div class="paragraph">
<p>KeyedProcessFunction用来操作KeyedStream。KeyedProcessFunction会处理流的每一个元素，输出为0个、1个或者多个元素。所有的Process Function都继承自RichFunction接口，所以都有open()、close()和getRuntimeContext()等方法。而KeyedProcessFunction[KEY, IN, OUT]还额外提供了两个方法:</p>
</div>
<div class="ulist">
<ul>
<li>
<p>processElement(v: IN, ctx: Context, out: Collector[OUT]), 流中的每一个元素都会调用这个方法，调用结果将会放在Collector数据类型中输出。Context可以访问元素的时间戳，元素的key，以及TimerService时间服务。Context还可以将结果输出到别的流(side outputs)。</p>
</li>
<li>
<p>onTimer(timestamp: Long, ctx: OnTimerContext, out: Collector[OUT])是一个回调函数。当之前注册的定时器触发时调用。参数timestamp为定时器所设定的触发的时间戳。Collector为输出结果的集合。OnTimerContext和processElement的Context参数一样，提供了上下文的一些信息，例如firing trigger的时间信息(事件时间或者处理时间)。</p>
</li>
</ul>
</div>
<div class="sect3">
<h4 id="_timerservice_and_timers">6.2.1. TimerService and Timers</h4>
<div class="paragraph">
<p>Context和OnTimerContext所持有的TimerService对象拥有以下方法:</p>
</div>
<div class="ulist">
<ul>
<li>
<p><code>currentProcessingTime(): Long</code> 返回当前处理时间</p>
</li>
<li>
<p><code>currentWatermark(): Long</code> 返回当前水位线的时间戳</p>
</li>
<li>
<p><code>registerProcessingTimeTimer(timestamp: Long): Unit</code> 会注册当前key的processing time的timer。当processing time到达定时时间时，触发timer。</p>
</li>
<li>
<p><code>registerEventTimeTimer(timestamp: Long): Unit</code> 会注册当前key的event time timer。当水位线大于等于定时器注册的时间时，触发定时器执行回调函数。</p>
</li>
<li>
<p><code>deleteProcessingTimeTimer(timestamp: Long): Unit</code> 删除之前注册处理时间定时器。如果没有这个时间戳的定时器，则不执行。</p>
</li>
<li>
<p><code>deleteEventTimeTimer(timestamp: Long): Unit</code> 删除之前注册的事件时间定时器，如果没有此时间戳的定时器，则不执行。</p>
</li>
</ul>
</div>
<div class="paragraph">
<p>当定时器timer触发时，执行回调函数onTimer()。processElement()方法和onTimer()方法是同步（不是异步）方法，这样可以避免并发访问和操作状态。</p>
</div>
<div class="admonitionblock note">
<table>
<tr>
<td class="icon">
<i class="fa icon-note" title="Note"></i>
</td>
<td class="content">
定时器timer只能在KeyedStream上面使用。
</td>
</tr>
</table>
</div>
<div class="paragraph">
<p>针对每一个key和timestamp，只能注册一个定期器。也就是说，每一个key可以注册多个定时器，但在每一个时间戳只能注册一个定时器。KeyedProcessFunction默认将所有定时器的时间戳放在一个优先队列中。在Flink做检查点操作时，定时器也会被保存到状态后端中。</p>
</div>
<div class="paragraph">
<p>举个例子说明KeyedProcessFunction如何操作KeyedStream。</p>
</div>
<div class="paragraph">
<p>下面的程序展示了如何监控温度传感器的温度值，如果温度值在一秒钟之内(processing time)连续上升，报警。</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="pygments highlight"><code data-lang="scala"><span></span><span class="tok-k">val</span> <span class="tok-n">warnings</span> <span class="tok-k">=</span> <span class="tok-n">readings</span>
  <span class="tok-c1">// key by sensor id</span>
  <span class="tok-o">.</span><span class="tok-n">keyBy</span><span class="tok-o">(</span><span class="tok-k">_</span><span class="tok-o">.</span><span class="tok-n">id</span><span class="tok-o">)</span>
  <span class="tok-c1">// apply ProcessFunction to monitor temperatures</span>
  <span class="tok-o">.</span><span class="tok-n">process</span><span class="tok-o">(</span><span class="tok-k">new</span> <span class="tok-nc">TempIncreaseAlertFunction</span><span class="tok-o">)</span></code></pre>
</div>
</div>
<div class="paragraph">
<p>看一下TempIncreaseAlertFunction如何实现, 程序中使用了ValueState这样一个状态变量, 后面会详细讲解。</p>
</div>
<div class="listingblock">
<div class="title">Example6_5.scala</div>
<div class="content">
<pre class="pygments highlight"><code data-lang="scala"><span></span><span class="tok-k">class</span> <span class="tok-nc">TempIncreaseAlertFunction</span> <span class="tok-k">extends</span> <span class="tok-nc">KeyedProcessFunction</span><span class="tok-o">[</span><span class="tok-kt">String</span>, <span class="tok-kt">SensorReading</span>, <span class="tok-kt">String</span><span class="tok-o">]</span> <span class="tok-o">{</span>
  <span class="tok-c1">// 保存上一个传感器温度值</span>
  <span class="tok-k">lazy</span> <span class="tok-k">val</span> <span class="tok-n">lastTemp</span><span class="tok-k">:</span> <span class="tok-kt">ValueState</span><span class="tok-o">[</span><span class="tok-kt">Double</span><span class="tok-o">]</span> <span class="tok-k">=</span> <span class="tok-n">getRuntimeContext</span><span class="tok-o">.</span><span class="tok-n">getState</span><span class="tok-o">(</span>
    <span class="tok-k">new</span> <span class="tok-nc">ValueStateDescriptor</span><span class="tok-o">[</span><span class="tok-kt">Double</span><span class="tok-o">](</span><span class="tok-s">&quot;lastTemp&quot;</span><span class="tok-o">,</span> <span class="tok-nc">Types</span><span class="tok-o">.</span><span class="tok-n">of</span><span class="tok-o">[</span><span class="tok-kt">Double</span><span class="tok-o">])</span>
  <span class="tok-o">)</span>

  <span class="tok-c1">// 保存注册的定时器的时间戳</span>
  <span class="tok-k">lazy</span> <span class="tok-k">val</span> <span class="tok-n">currentTimer</span><span class="tok-k">:</span> <span class="tok-kt">ValueState</span><span class="tok-o">[</span><span class="tok-kt">Long</span><span class="tok-o">]</span> <span class="tok-k">=</span> <span class="tok-n">getRuntimeContext</span><span class="tok-o">.</span><span class="tok-n">getState</span><span class="tok-o">(</span>
    <span class="tok-k">new</span> <span class="tok-nc">ValueStateDescriptor</span><span class="tok-o">[</span><span class="tok-kt">Long</span><span class="tok-o">](</span><span class="tok-s">&quot;timer&quot;</span><span class="tok-o">,</span> <span class="tok-nc">Types</span><span class="tok-o">.</span><span class="tok-n">of</span><span class="tok-o">[</span><span class="tok-kt">Long</span><span class="tok-o">])</span>
  <span class="tok-o">)</span>

  <span class="tok-k">override</span> <span class="tok-k">def</span> <span class="tok-n">processElement</span><span class="tok-o">(</span><span class="tok-n">r</span><span class="tok-k">:</span> <span class="tok-kt">SensorReading</span><span class="tok-o">,</span>
                              <span class="tok-n">ctx</span><span class="tok-k">:</span> <span class="tok-kt">KeyedProcessFunction</span><span class="tok-o">[</span><span class="tok-kt">String</span>, <span class="tok-kt">SensorReading</span>, <span class="tok-kt">String</span><span class="tok-o">]</span><span class="tok-k">#</span><span class="tok-nc">Context</span><span class="tok-o">,</span>
                              <span class="tok-n">out</span><span class="tok-k">:</span> <span class="tok-kt">Collector</span><span class="tok-o">[</span><span class="tok-kt">String</span><span class="tok-o">])</span><span class="tok-k">:</span> <span class="tok-kt">Unit</span> <span class="tok-o">=</span> <span class="tok-o">{</span>
    <span class="tok-c1">// get previous temperature</span>
    <span class="tok-c1">// 取出上一次的温度</span>
    <span class="tok-k">val</span> <span class="tok-n">prevTemp</span> <span class="tok-k">=</span> <span class="tok-n">lastTemp</span><span class="tok-o">.</span><span class="tok-n">value</span><span class="tok-o">()</span>
    <span class="tok-c1">// update last temperature</span>
    <span class="tok-c1">// 将当前温度更新到上一次的温度这个变量中</span>
    <span class="tok-n">lastTemp</span><span class="tok-o">.</span><span class="tok-n">update</span><span class="tok-o">(</span><span class="tok-n">r</span><span class="tok-o">.</span><span class="tok-n">temperature</span><span class="tok-o">)</span>

    <span class="tok-k">val</span> <span class="tok-n">curTimerTimestamp</span> <span class="tok-k">=</span> <span class="tok-n">currentTimer</span><span class="tok-o">.</span><span class="tok-n">value</span><span class="tok-o">()</span>
    <span class="tok-k">if</span> <span class="tok-o">(</span><span class="tok-n">prevTemp</span> <span class="tok-o">==</span> <span class="tok-mf">0.0</span> <span class="tok-o">||</span> <span class="tok-n">r</span><span class="tok-o">.</span><span class="tok-n">temperature</span> <span class="tok-o">&lt;</span> <span class="tok-n">prevTemp</span><span class="tok-o">)</span> <span class="tok-o">{</span>
      <span class="tok-c1">// temperature decreased; delete current timer</span>
      <span class="tok-c1">// 温度下降或者是第一个温度值，删除定时器</span>
      <span class="tok-n">ctx</span><span class="tok-o">.</span><span class="tok-n">timerService</span><span class="tok-o">().</span><span class="tok-n">deleteProcessingTimeTimer</span><span class="tok-o">(</span><span class="tok-n">curTimerTimestamp</span><span class="tok-o">)</span>
      <span class="tok-c1">// 清空状态变量</span>
      <span class="tok-n">currentTimer</span><span class="tok-o">.</span><span class="tok-n">clear</span><span class="tok-o">()</span>
    <span class="tok-o">}</span> <span class="tok-k">else</span> <span class="tok-k">if</span> <span class="tok-o">(</span><span class="tok-n">r</span><span class="tok-o">.</span><span class="tok-n">temperature</span> <span class="tok-o">&gt;</span> <span class="tok-n">prevTemp</span> <span class="tok-o">&amp;&amp;</span> <span class="tok-n">curTimerTimestamp</span> <span class="tok-o">==</span> <span class="tok-mi">0</span><span class="tok-o">)</span> <span class="tok-o">{</span>
      <span class="tok-c1">// temperature increased and we have not set a timer yet</span>
      <span class="tok-c1">// set processing time timer for now + 1 second</span>
      <span class="tok-c1">// 温度上升且我们并没有设置定时器</span>
      <span class="tok-k">val</span> <span class="tok-n">timerTs</span> <span class="tok-k">=</span> <span class="tok-n">ctx</span><span class="tok-o">.</span><span class="tok-n">timerService</span><span class="tok-o">().</span><span class="tok-n">currentProcessingTime</span><span class="tok-o">()</span> <span class="tok-o">+</span> <span class="tok-mi">1000</span>
      <span class="tok-n">ctx</span><span class="tok-o">.</span><span class="tok-n">timerService</span><span class="tok-o">().</span><span class="tok-n">registerProcessingTimeTimer</span><span class="tok-o">(</span><span class="tok-n">timerTs</span><span class="tok-o">)</span>
      <span class="tok-c1">// remember current timer</span>
      <span class="tok-n">currentTimer</span><span class="tok-o">.</span><span class="tok-n">update</span><span class="tok-o">(</span><span class="tok-n">timerTs</span><span class="tok-o">)</span>
    <span class="tok-o">}</span>
  <span class="tok-o">}</span>

  <span class="tok-k">override</span> <span class="tok-k">def</span> <span class="tok-n">onTimer</span><span class="tok-o">(</span><span class="tok-n">ts</span><span class="tok-k">:</span> <span class="tok-kt">Long</span><span class="tok-o">,</span>
                       <span class="tok-n">ctx</span><span class="tok-k">:</span> <span class="tok-kt">KeyedProcessFunction</span><span class="tok-o">[</span><span class="tok-kt">String</span>, <span class="tok-kt">SensorReading</span>, <span class="tok-kt">String</span><span class="tok-o">]</span><span class="tok-k">#</span><span class="tok-nc">OnTimerContext</span><span class="tok-o">,</span>
                       <span class="tok-n">out</span><span class="tok-k">:</span> <span class="tok-kt">Collector</span><span class="tok-o">[</span><span class="tok-kt">String</span><span class="tok-o">])</span><span class="tok-k">:</span> <span class="tok-kt">Unit</span> <span class="tok-o">=</span> <span class="tok-o">{</span>
    <span class="tok-n">out</span><span class="tok-o">.</span><span class="tok-n">collect</span><span class="tok-o">(</span><span class="tok-s">&quot;传感器id为: &quot;</span> <span class="tok-o">+</span> <span class="tok-n">ctx</span><span class="tok-o">.</span><span class="tok-n">getCurrentKey</span> <span class="tok-o">+</span> <span class="tok-s">&quot;的传感器温度值已经连续1s上升了。&quot;</span><span class="tok-o">)</span>
    <span class="tok-n">currentTimer</span><span class="tok-o">.</span><span class="tok-n">clear</span><span class="tok-o">()</span>
  <span class="tok-o">}</span>
<span class="tok-o">}</span></code></pre>
</div>
</div>
</div>
<div class="sect3">
<h4 id="_将事件发送到侧输出emitting_to_side_outputs">6.2.2. 将事件发送到侧输出(Emitting to Side Outputs)</h4>
<div class="paragraph">
<p>大部分的DataStream API的算子的输出是单一输出，也就是某种数据类型的流。除了split算子，可以将一条流分成多条流，这些流的数据类型也都相同。process function的side outputs功能可以产生多条流，并且这些流的数据类型可以不一样。一个side output可以定义为OutputTag[X]对象，X是输出流的数据类型。process function可以通过Context对象发射一个事件到一个或者多个side outputs。</p>
</div>
<div class="paragraph">
<p>例子</p>
</div>
<div class="listingblock">
<div class="title">Example 6-6</div>
<div class="content">
<pre class="pygments highlight"><code data-lang="scala"><span></span><span class="tok-k">val</span> <span class="tok-n">monitoredReadings</span><span class="tok-k">:</span> <span class="tok-kt">DataStream</span><span class="tok-o">[</span><span class="tok-kt">SensorReading</span><span class="tok-o">]</span> <span class="tok-k">=</span> <span class="tok-n">readings</span>
  <span class="tok-o">.</span><span class="tok-n">process</span><span class="tok-o">(</span><span class="tok-k">new</span> <span class="tok-nc">FreezingMonitor</span><span class="tok-o">)</span>

<span class="tok-n">monitoredReadings</span>
  <span class="tok-o">.</span><span class="tok-n">getSideOutput</span><span class="tok-o">(</span><span class="tok-k">new</span> <span class="tok-nc">OutputTag</span><span class="tok-o">[</span><span class="tok-kt">String</span><span class="tok-o">](</span><span class="tok-s">&quot;freezing-alarms&quot;</span><span class="tok-o">))</span>
  <span class="tok-o">.</span><span class="tok-n">print</span><span class="tok-o">()</span>

<span class="tok-n">readings</span><span class="tok-o">.</span><span class="tok-n">print</span><span class="tok-o">()</span></code></pre>
</div>
</div>
<div class="paragraph">
<p>接下来我们实现FreezingMonitor函数，用来监控传感器温度值，将温度值低于32F的温度输出到side output。</p>
</div>
<div class="listingblock">
<div class="title">Example 6-7</div>
<div class="content">
<pre class="pygments highlight"><code data-lang="scala"><span></span><span class="tok-k">class</span> <span class="tok-nc">FreezingMonitor</span> <span class="tok-k">extends</span> <span class="tok-nc">ProcessFunction</span><span class="tok-o">[</span><span class="tok-kt">SensorReading</span>, <span class="tok-kt">SensorReading</span><span class="tok-o">]</span> <span class="tok-o">{</span>
  <span class="tok-c1">// define a side output tag</span>
  <span class="tok-c1">// 定义一个侧输出标签</span>
  <span class="tok-k">lazy</span> <span class="tok-k">val</span> <span class="tok-n">freezingAlarmOutput</span><span class="tok-k">:</span> <span class="tok-kt">OutputTag</span><span class="tok-o">[</span><span class="tok-kt">String</span><span class="tok-o">]</span> <span class="tok-k">=</span>
    <span class="tok-k">new</span> <span class="tok-nc">OutputTag</span><span class="tok-o">[</span><span class="tok-kt">String</span><span class="tok-o">](</span><span class="tok-s">&quot;freezing-alarms&quot;</span><span class="tok-o">)</span>

  <span class="tok-k">override</span> <span class="tok-k">def</span> <span class="tok-n">processElement</span><span class="tok-o">(</span><span class="tok-n">r</span><span class="tok-k">:</span> <span class="tok-kt">SensorReading</span><span class="tok-o">,</span>
                              <span class="tok-n">ctx</span><span class="tok-k">:</span> <span class="tok-kt">ProcessFunction</span><span class="tok-o">[</span><span class="tok-kt">SensorReading</span>, <span class="tok-kt">SensorReading</span><span class="tok-o">]</span><span class="tok-k">#</span><span class="tok-nc">Context</span><span class="tok-o">,</span>
                              <span class="tok-n">out</span><span class="tok-k">:</span> <span class="tok-kt">Collector</span><span class="tok-o">[</span><span class="tok-kt">SensorReading</span><span class="tok-o">])</span><span class="tok-k">:</span> <span class="tok-kt">Unit</span> <span class="tok-o">=</span> <span class="tok-o">{</span>
    <span class="tok-c1">// emit freezing alarm if temperature is below 32F</span>
    <span class="tok-k">if</span> <span class="tok-o">(</span><span class="tok-n">r</span><span class="tok-o">.</span><span class="tok-n">temperature</span> <span class="tok-o">&lt;</span> <span class="tok-mf">32.0</span><span class="tok-o">)</span> <span class="tok-o">{</span>
      <span class="tok-n">ctx</span><span class="tok-o">.</span><span class="tok-n">output</span><span class="tok-o">(</span><span class="tok-n">freezingAlarmOutput</span><span class="tok-o">,</span> <span class="tok-s">s&quot;Freezing Alarm for </span><span class="tok-si">${</span><span class="tok-n">r</span><span class="tok-o">.</span><span class="tok-n">id</span><span class="tok-si">}</span><span class="tok-s">&quot;</span><span class="tok-o">)</span>
    <span class="tok-o">}</span>
    <span class="tok-c1">// forward all readings to the regular output</span>
    <span class="tok-n">out</span><span class="tok-o">.</span><span class="tok-n">collect</span><span class="tok-o">(</span><span class="tok-n">r</span><span class="tok-o">)</span>
  <span class="tok-o">}</span>
<span class="tok-o">}</span></code></pre>
</div>
</div>
</div>
<div class="sect3">
<h4 id="_coprocessfunction">6.2.3. CoProcessFunction</h4>
<div class="paragraph">
<p>对于两条输入流，DataStream API提供了CoProcessFunction这样的low-level操作。CoProcessFunction提供了操作每一个输入流的方法: processElement1()和processElement2()。类似于ProcessFunction，这两种方法都通过Context对象来调用。这个Context对象可以访问事件数据，定时器时间戳，TimerService，以及side outputs。CoProcessFunction也提供了onTimer()回调函数。下面的例子展示了如何使用CoProcessFunction来合并两条流。</p>
</div>
<div class="listingblock">
<div class="title">Example 6-8</div>
<div class="content">
<pre class="pygments highlight"><code data-lang="scala"><span></span><span class="tok-c1">// ingest sensor stream</span>
<span class="tok-k">val</span> <span class="tok-n">readings</span><span class="tok-k">:</span> <span class="tok-kt">DataStream</span><span class="tok-o">[</span><span class="tok-kt">SensorReading</span><span class="tok-o">]</span> <span class="tok-k">=</span> <span class="tok-o">...</span>

<span class="tok-c1">// filter switches enable forwarding of readings</span>
<span class="tok-k">val</span> <span class="tok-n">filterSwitches</span><span class="tok-k">:</span> <span class="tok-kt">DataStream</span><span class="tok-o">[(</span><span class="tok-kt">String</span>, <span class="tok-kt">Long</span><span class="tok-o">)]</span> <span class="tok-k">=</span> <span class="tok-n">env</span>
  <span class="tok-o">.</span><span class="tok-n">fromCollection</span><span class="tok-o">(</span><span class="tok-nc">Seq</span><span class="tok-o">(</span>
    <span class="tok-o">(</span><span class="tok-s">&quot;sensor_2&quot;</span><span class="tok-o">,</span> <span class="tok-mi">10</span> <span class="tok-o">*</span> <span class="tok-mi">1000L</span><span class="tok-o">),</span>
    <span class="tok-o">(</span><span class="tok-s">&quot;sensor_7&quot;</span><span class="tok-o">,</span> <span class="tok-mi">60</span> <span class="tok-o">*</span> <span class="tok-mi">1000L</span><span class="tok-o">)</span>
  <span class="tok-o">))</span>

<span class="tok-k">val</span> <span class="tok-n">forwardedReadings</span> <span class="tok-k">=</span> <span class="tok-n">readings</span>
  <span class="tok-c1">// connect readings and switches</span>
  <span class="tok-o">.</span><span class="tok-n">connect</span><span class="tok-o">(</span><span class="tok-n">filterSwitches</span><span class="tok-o">)</span>
  <span class="tok-c1">// key by sensor ids</span>
  <span class="tok-o">.</span><span class="tok-n">keyBy</span><span class="tok-o">(</span><span class="tok-k">_</span><span class="tok-o">.</span><span class="tok-n">id</span><span class="tok-o">,</span> <span class="tok-k">_</span><span class="tok-o">.</span><span class="tok-n">_1</span><span class="tok-o">)</span>
  <span class="tok-c1">// apply filtering CoProcessFunction</span>
  <span class="tok-o">.</span><span class="tok-n">process</span><span class="tok-o">(</span><span class="tok-k">new</span> <span class="tok-nc">ReadingFilter</span><span class="tok-o">)</span></code></pre>
</div>
</div>
<div class="listingblock">
<div class="title">Example 6-9</div>
<div class="content">
<pre class="pygments highlight"><code data-lang="scala"><span></span><span class="tok-k">class</span> <span class="tok-nc">ReadingFilter</span> <span class="tok-k">extends</span> <span class="tok-nc">CoProcessFunction</span><span class="tok-o">[</span><span class="tok-kt">SensorReading</span>, <span class="tok-o">(</span><span class="tok-kt">String</span>, <span class="tok-kt">Long</span><span class="tok-o">)</span>, <span class="tok-kt">SensorReading</span><span class="tok-o">]</span> <span class="tok-o">{</span>
  <span class="tok-c1">// switch to enable forwarding</span>
  <span class="tok-c1">// 传送数据的开关</span>
  <span class="tok-k">lazy</span> <span class="tok-k">val</span> <span class="tok-n">forwardingEnabled</span><span class="tok-k">:</span> <span class="tok-kt">ValueState</span><span class="tok-o">[</span><span class="tok-kt">Boolean</span><span class="tok-o">]</span> <span class="tok-k">=</span> <span class="tok-n">getRuntimeContext</span><span class="tok-o">.</span><span class="tok-n">getState</span><span class="tok-o">(</span>
    <span class="tok-k">new</span> <span class="tok-nc">ValueStateDescriptor</span><span class="tok-o">[</span><span class="tok-kt">Boolean</span><span class="tok-o">](</span><span class="tok-s">&quot;filterSwitch&quot;</span><span class="tok-o">,</span> <span class="tok-nc">Types</span><span class="tok-o">.</span><span class="tok-n">of</span><span class="tok-o">[</span><span class="tok-kt">Boolean</span><span class="tok-o">]))</span>

  <span class="tok-c1">// hold timestamp of currently active disable timer</span>
  <span class="tok-k">lazy</span> <span class="tok-k">val</span> <span class="tok-n">disableTimer</span><span class="tok-k">:</span> <span class="tok-kt">ValueState</span><span class="tok-o">[</span><span class="tok-kt">Long</span><span class="tok-o">]</span> <span class="tok-k">=</span> <span class="tok-n">getRuntimeContext</span><span class="tok-o">.</span><span class="tok-n">getState</span><span class="tok-o">(</span><span class="tok-k">new</span> <span class="tok-nc">ValueStateDescriptor</span><span class="tok-o">[</span><span class="tok-kt">Long</span><span class="tok-o">](</span><span class="tok-s">&quot;timer&quot;</span><span class="tok-o">,</span> <span class="tok-nc">Types</span><span class="tok-o">.</span><span class="tok-n">of</span><span class="tok-o">[</span><span class="tok-kt">Long</span><span class="tok-o">]))</span>

  <span class="tok-k">override</span> <span class="tok-k">def</span> <span class="tok-n">processElement1</span><span class="tok-o">(</span><span class="tok-n">reading</span><span class="tok-k">:</span> <span class="tok-kt">SensorReading</span><span class="tok-o">,</span>
                               <span class="tok-n">ctx</span><span class="tok-k">:</span> <span class="tok-kt">CoProcessFunction</span><span class="tok-o">[</span><span class="tok-kt">SensorReading</span>, <span class="tok-o">(</span><span class="tok-kt">String</span>, <span class="tok-kt">Long</span><span class="tok-o">)</span>, <span class="tok-kt">SensorReading</span><span class="tok-o">]</span><span class="tok-k">#</span><span class="tok-nc">Context</span><span class="tok-o">,</span>
                               <span class="tok-n">out</span><span class="tok-k">:</span> <span class="tok-kt">Collector</span><span class="tok-o">[</span><span class="tok-kt">SensorReading</span><span class="tok-o">])</span><span class="tok-k">:</span> <span class="tok-kt">Unit</span> <span class="tok-o">=</span> <span class="tok-o">{</span>
    <span class="tok-c1">// check if we may forward the reading</span>
    <span class="tok-c1">// 决定我们是否要将数据继续传下去</span>
    <span class="tok-k">if</span> <span class="tok-o">(</span><span class="tok-n">forwardingEnabled</span><span class="tok-o">.</span><span class="tok-n">value</span><span class="tok-o">())</span> <span class="tok-o">{</span>
      <span class="tok-n">out</span><span class="tok-o">.</span><span class="tok-n">collect</span><span class="tok-o">(</span><span class="tok-n">reading</span><span class="tok-o">)</span>
    <span class="tok-o">}</span>
  <span class="tok-o">}</span>

  <span class="tok-k">override</span> <span class="tok-k">def</span> <span class="tok-n">processElement2</span><span class="tok-o">(</span><span class="tok-n">switch</span><span class="tok-k">:</span> <span class="tok-o">(</span><span class="tok-kt">String</span><span class="tok-o">,</span> <span class="tok-kt">Long</span><span class="tok-o">),</span>
                               <span class="tok-n">ctx</span><span class="tok-k">:</span> <span class="tok-kt">CoProcessFunction</span><span class="tok-o">[</span><span class="tok-kt">SensorReading</span>, <span class="tok-o">(</span><span class="tok-kt">String</span>, <span class="tok-kt">Long</span><span class="tok-o">)</span>, <span class="tok-kt">SensorReading</span><span class="tok-o">]</span><span class="tok-k">#</span><span class="tok-nc">Context</span><span class="tok-o">,</span>
                               <span class="tok-n">out</span><span class="tok-k">:</span> <span class="tok-kt">Collector</span><span class="tok-o">[</span><span class="tok-kt">SensorReading</span><span class="tok-o">])</span><span class="tok-k">:</span> <span class="tok-kt">Unit</span> <span class="tok-o">=</span> <span class="tok-o">{</span>
    <span class="tok-c1">// enable reading forwarding</span>
    <span class="tok-c1">// 允许继续传输数据</span>
    <span class="tok-n">forwardingEnabled</span><span class="tok-o">.</span><span class="tok-n">update</span><span class="tok-o">(</span><span class="tok-kc">true</span><span class="tok-o">)</span>
    <span class="tok-c1">// set disable forward timer</span>
    <span class="tok-k">val</span> <span class="tok-n">timerTimestamp</span> <span class="tok-k">=</span> <span class="tok-n">ctx</span><span class="tok-o">.</span><span class="tok-n">timerService</span><span class="tok-o">().</span><span class="tok-n">currentProcessingTime</span><span class="tok-o">()</span> <span class="tok-o">+</span> <span class="tok-n">switch</span><span class="tok-o">.</span><span class="tok-n">_2</span>
    <span class="tok-k">val</span> <span class="tok-n">curTimerTimestamp</span> <span class="tok-k">=</span> <span class="tok-n">disableTimer</span><span class="tok-o">.</span><span class="tok-n">value</span><span class="tok-o">()</span>

    <span class="tok-k">if</span> <span class="tok-o">(</span><span class="tok-n">timerTimestamp</span> <span class="tok-o">&gt;</span> <span class="tok-n">curTimerTimestamp</span><span class="tok-o">)</span> <span class="tok-o">{</span>
      <span class="tok-c1">// remove current timer and register new timer</span>
      <span class="tok-n">ctx</span><span class="tok-o">.</span><span class="tok-n">timerService</span><span class="tok-o">().</span><span class="tok-n">deleteProcessingTimeTimer</span><span class="tok-o">(</span><span class="tok-n">curTimerTimestamp</span><span class="tok-o">)</span>
      <span class="tok-n">ctx</span><span class="tok-o">.</span><span class="tok-n">timerService</span><span class="tok-o">().</span><span class="tok-n">registerProcessingTimeTimer</span><span class="tok-o">(</span><span class="tok-n">timerTimestamp</span><span class="tok-o">)</span>
      <span class="tok-n">disableTimer</span><span class="tok-o">.</span><span class="tok-n">update</span><span class="tok-o">(</span><span class="tok-n">timerTimestamp</span><span class="tok-o">)</span>
    <span class="tok-o">}</span>
  <span class="tok-o">}</span>

  <span class="tok-k">override</span> <span class="tok-k">def</span> <span class="tok-n">onTimer</span><span class="tok-o">(</span><span class="tok-n">ts</span><span class="tok-k">:</span> <span class="tok-kt">Long</span><span class="tok-o">,</span>
                       <span class="tok-n">ctx</span><span class="tok-k">:</span> <span class="tok-kt">CoProcessFunction</span><span class="tok-o">[</span><span class="tok-kt">SensorReading</span>, <span class="tok-o">(</span><span class="tok-kt">String</span>, <span class="tok-kt">Long</span><span class="tok-o">)</span>, <span class="tok-kt">SensorReading</span><span class="tok-o">]</span><span class="tok-k">#</span><span class="tok-nc">OnTimerContext</span><span class="tok-o">,</span>
                       <span class="tok-n">out</span><span class="tok-k">:</span> <span class="tok-kt">Collector</span><span class="tok-o">[</span><span class="tok-kt">SensorReading</span><span class="tok-o">])</span><span class="tok-k">:</span> <span class="tok-kt">Unit</span> <span class="tok-o">=</span> <span class="tok-o">{</span>
     <span class="tok-c1">// remove all state; forward switch will be false by default</span>
     <span class="tok-n">forwardingEnabled</span><span class="tok-o">.</span><span class="tok-n">clear</span><span class="tok-o">()</span>
     <span class="tok-n">disableTimer</span><span class="tok-o">.</span><span class="tok-n">clear</span><span class="tok-o">()</span>
  <span class="tok-o">}</span>
<span class="tok-o">}</span></code></pre>
</div>
</div>
</div>
</div>
<div class="sect2">
<h3 id="_窗口操作符window_operators">6.3. 窗口操作符(Window Operators)</h3>
<div class="paragraph">
<p>窗口操作是流处理程序中很常见的操作。窗口操作允许我们在无限流上的一段有界区间上面做聚合之类的操作。而我们使用基于时间的逻辑来定义区间。窗口操作符提供了一种将数据放进一个桶，并根据桶中的数据做计算的方法。例如，我们可以将事件放进5分钟的滚动窗口中，然后计数。</p>
</div>
<div class="admonitionblock note">
<table>
<tr>
<td class="icon">
<i class="fa icon-note" title="Note"></i>
</td>
<td class="content">
无限流转化成有限数据的方法：使用窗口。
</td>
</tr>
</table>
</div>
<div class="sect3">
<h4 id="_定义窗口操作符">6.3.1. 定义窗口操作符</h4>
<div class="paragraph">
<p>Window算子可以在keyed stream或者nokeyed stream上面使用。</p>
</div>
<div class="paragraph">
<p>创建一个Window算子，需要指定两个部分：</p>
</div>
<div class="olist arabic">
<ol class="arabic">
<li>
<p><code>window assigner</code>定义了流的元素如何分配到window中。window assigner将会产生一条WindowedStream(或者AllWindowedStream，如果是nonkeyed DataStream的话)</p>
</li>
<li>
<p>window function用来处理WindowedStream(AllWindowedStream)中的元素。</p>
</li>
</ol>
</div>
<div class="paragraph">
<p>下面的代码说明了如何使用窗口操作符。</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="pygments highlight"><code data-lang="scala"><span></span><span class="tok-n">stream</span>
  <span class="tok-o">.</span><span class="tok-n">keyBy</span><span class="tok-o">(...)</span>
  <span class="tok-o">.</span><span class="tok-n">window</span><span class="tok-o">(...)</span>  <span class="tok-c1">// 指定window assigner</span>
  <span class="tok-o">.</span><span class="tok-n">reduce</span><span class="tok-o">/</span><span class="tok-n">aggregate</span><span class="tok-o">/</span><span class="tok-n">process</span><span class="tok-o">(...)</span> <span class="tok-c1">// 指定window function</span>

<span class="tok-n">stream</span>
  <span class="tok-o">.</span><span class="tok-n">windowAll</span><span class="tok-o">(...)</span> <span class="tok-c1">// 指定window assigner</span>
  <span class="tok-o">.</span><span class="tok-n">reduce</span><span class="tok-o">/</span><span class="tok-n">aggregate</span><span class="tok-o">/</span><span class="tok-n">process</span><span class="tok-o">(...)</span> <span class="tok-c1">// 指定window function</span></code></pre>
</div>
</div>
<div class="admonitionblock note">
<table>
<tr>
<td class="icon">
<i class="fa icon-note" title="Note"></i>
</td>
<td class="content">
我们的学习重点是Keyed WindowedStream。
</td>
</tr>
</table>
</div>
</div>
<div class="sect3">
<h4 id="_内置的窗口分配器built_in_window_assigner">6.3.2. 内置的窗口分配器(built-in window assigner)</h4>
<div class="paragraph">
<p>窗口分配器将会根据事件的事件时间或者处理时间来将事件分配到对应的窗口中去。窗口包含开始时间和结束时间这两个时间戳。</p>
</div>
<div class="paragraph">
<p>所有的窗口分配器都包含一个默认的触发器：</p>
</div>
<div class="ulist">
<ul>
<li>
<p>对于事件时间：当水位线超过窗口结束时间，触发窗口的求值操作。</p>
</li>
<li>
<p>对于处理时间：当机器时间超过窗口结束时间，触发窗口的求值操作。</p>
</li>
</ul>
</div>
<div class="admonitionblock note">
<table>
<tr>
<td class="icon">
<i class="fa icon-note" title="Note"></i>
</td>
<td class="content">
需要注意的是：当处于某个窗口的第一个事件到达的时候，这个窗口才会被创建。Flink不会对空窗口求值。
</td>
</tr>
</table>
</div>
<div class="paragraph">
<p>Flink创建的窗口类型是<code>TimeWindow</code>，包含开始时间和结束时间，区间是左闭右开的，也就是说包含开始时间戳，不包含结束时间戳。</p>
</div>
<div class="paragraph">
<p><strong>滚动窗口(tumbling windows)</strong></p>
</div>
<div class="imageblock">
<div class="content">
<img src="images/spaf_0601.png" alt="spaf 0601">
</div>
</div>
<div class="listingblock">
<div class="content">
<pre class="pygments highlight"><code data-lang="scala"><span></span><span class="tok-k">val</span> <span class="tok-n">sensorData</span><span class="tok-k">:</span> <span class="tok-kt">DataStream</span><span class="tok-o">[</span><span class="tok-kt">SensorReading</span><span class="tok-o">]</span> <span class="tok-k">=</span> <span class="tok-o">...</span>

<span class="tok-k">val</span> <span class="tok-n">avgTemp</span> <span class="tok-k">=</span> <span class="tok-n">sensorData</span>
  <span class="tok-o">.</span><span class="tok-n">keyBy</span><span class="tok-o">(</span><span class="tok-k">_</span><span class="tok-o">.</span><span class="tok-n">id</span><span class="tok-o">)</span>
  <span class="tok-c1">// group readings in 1s event-time windows</span>
  <span class="tok-o">.</span><span class="tok-n">window</span><span class="tok-o">(</span><span class="tok-nc">TumblingEventTimeWindows</span><span class="tok-o">.</span><span class="tok-n">of</span><span class="tok-o">(</span><span class="tok-nc">Time</span><span class="tok-o">.</span><span class="tok-n">seconds</span><span class="tok-o">(</span><span class="tok-mi">1</span><span class="tok-o">)))</span>
  <span class="tok-o">.</span><span class="tok-n">process</span><span class="tok-o">(</span><span class="tok-k">new</span> <span class="tok-nc">TemperatureAverager</span><span class="tok-o">)</span>

<span class="tok-k">val</span> <span class="tok-n">avgTemp</span> <span class="tok-k">=</span> <span class="tok-n">sensorData</span>
  <span class="tok-o">.</span><span class="tok-n">keyBy</span><span class="tok-o">(</span><span class="tok-k">_</span><span class="tok-o">.</span><span class="tok-n">id</span><span class="tok-o">)</span>
  <span class="tok-c1">// group readings in 1s processing-time windows</span>
  <span class="tok-o">.</span><span class="tok-n">window</span><span class="tok-o">(</span><span class="tok-nc">TumblingProcessingTimeWindows</span><span class="tok-o">.</span><span class="tok-n">of</span><span class="tok-o">(</span><span class="tok-nc">Time</span><span class="tok-o">.</span><span class="tok-n">seconds</span><span class="tok-o">(</span><span class="tok-mi">1</span><span class="tok-o">)))</span>
  <span class="tok-o">.</span><span class="tok-n">process</span><span class="tok-o">(</span><span class="tok-k">new</span> <span class="tok-nc">TemperatureAverager</span><span class="tok-o">)</span>

<span class="tok-c1">// 其实就是之前的</span>
<span class="tok-c1">// shortcut for window.(TumblingEventTimeWindows.of(size))</span>
<span class="tok-k">val</span> <span class="tok-n">avgTemp</span> <span class="tok-k">=</span> <span class="tok-n">sensorData</span>
  <span class="tok-o">.</span><span class="tok-n">keyBy</span><span class="tok-o">(</span><span class="tok-k">_</span><span class="tok-o">.</span><span class="tok-n">id</span><span class="tok-o">)</span>
  <span class="tok-o">.</span><span class="tok-n">timeWindow</span><span class="tok-o">(</span><span class="tok-nc">Time</span><span class="tok-o">.</span><span class="tok-n">seconds</span><span class="tok-o">(</span><span class="tok-mi">1</span><span class="tok-o">))</span>
  <span class="tok-o">.</span><span class="tok-n">process</span><span class="tok-o">(</span><span class="tok-k">new</span> <span class="tok-nc">TemperatureAverager</span><span class="tok-o">)</span></code></pre>
</div>
</div>
<div class="paragraph">
<p>默认情况下，滚动窗口会和<code>1970- 01-01-00:00:00.000</code>对齐，例如一个1小时的滚动窗口将会定义以下开始时间的窗口：00:00:00，01:00:00，02:00:00，等等。</p>
</div>
<div class="paragraph">
<p><strong>滑动窗口(sliding window)</strong></p>
</div>
<div class="paragraph">
<p>对于滑动窗口，我们需要指定窗口的大小和滑动的步长。当滑动步长小于窗口大小时，窗口将会出现重叠，而元素会被分配到不止一个窗口中去。当滑动步长大于窗口大小时，一些元素可能不会被分配到任何窗口中去，会被直接丢弃。</p>
</div>
<div class="paragraph">
<p>下面的代码定义了窗口大小为1小时，滑动步长为15分钟的窗口。每一个元素将被分配到4个窗口中去。</p>
</div>
<div class="imageblock">
<div class="content">
<img src="images/spaf_0602.png" alt="spaf 0602">
</div>
</div>
<div class="listingblock">
<div class="content">
<pre class="pygments highlight"><code data-lang="scala"><span></span><span class="tok-k">val</span> <span class="tok-n">slidingAvgTemp</span> <span class="tok-k">=</span> <span class="tok-n">sensorData</span>
  <span class="tok-o">.</span><span class="tok-n">keyBy</span><span class="tok-o">(</span><span class="tok-k">_</span><span class="tok-o">.</span><span class="tok-n">id</span><span class="tok-o">)</span>
  <span class="tok-o">.</span><span class="tok-n">window</span><span class="tok-o">(</span><span class="tok-nc">SlidingEventTimeWindows</span><span class="tok-o">.</span><span class="tok-n">of</span><span class="tok-o">(</span><span class="tok-nc">Time</span><span class="tok-o">.</span><span class="tok-n">hours</span><span class="tok-o">(</span><span class="tok-mi">1</span><span class="tok-o">),</span> <span class="tok-nc">Time</span><span class="tok-o">.</span><span class="tok-n">minutes</span><span class="tok-o">(</span><span class="tok-mi">15</span><span class="tok-o">)))</span>
  <span class="tok-o">.</span><span class="tok-n">process</span><span class="tok-o">(</span><span class="tok-k">new</span> <span class="tok-nc">TemperatureAverager</span><span class="tok-o">)</span>

<span class="tok-k">val</span> <span class="tok-n">slidingAvgTemp</span> <span class="tok-k">=</span> <span class="tok-n">sensorData</span>
  <span class="tok-o">.</span><span class="tok-n">keyBy</span><span class="tok-o">(</span><span class="tok-k">_</span><span class="tok-o">.</span><span class="tok-n">id</span><span class="tok-o">)</span>
  <span class="tok-o">.</span><span class="tok-n">window</span><span class="tok-o">(</span><span class="tok-nc">SlidingProcessingTimeWindows</span><span class="tok-o">.</span><span class="tok-n">of</span><span class="tok-o">(</span><span class="tok-nc">Time</span><span class="tok-o">.</span><span class="tok-n">hours</span><span class="tok-o">(</span><span class="tok-mi">1</span><span class="tok-o">),</span> <span class="tok-nc">Time</span><span class="tok-o">.</span><span class="tok-n">minutes</span><span class="tok-o">(</span><span class="tok-mi">15</span><span class="tok-o">)))</span>
  <span class="tok-o">.</span><span class="tok-n">process</span><span class="tok-o">(</span><span class="tok-k">new</span> <span class="tok-nc">TemperatureAverager</span><span class="tok-o">)</span>

<span class="tok-k">val</span> <span class="tok-n">slidingAvgTemp</span> <span class="tok-k">=</span> <span class="tok-n">sensorData</span>
  <span class="tok-o">.</span><span class="tok-n">keyBy</span><span class="tok-o">(</span><span class="tok-k">_</span><span class="tok-o">.</span><span class="tok-n">id</span><span class="tok-o">)</span>
  <span class="tok-o">.</span><span class="tok-n">timeWindow</span><span class="tok-o">(</span><span class="tok-nc">Time</span><span class="tok-o">.</span><span class="tok-n">hours</span><span class="tok-o">(</span><span class="tok-mi">1</span><span class="tok-o">),</span> <span class="tok-nc">Time</span><span class="tok-o">.</span><span class="tok-n">minutes</span><span class="tok-o">(</span><span class="tok-mi">15</span><span class="tok-o">))</span>
  <span class="tok-o">.</span><span class="tok-n">process</span><span class="tok-o">(</span><span class="tok-k">new</span> <span class="tok-nc">TemperatureAverager</span><span class="tok-o">)</span></code></pre>
</div>
</div>
<div class="paragraph">
<p><strong>会话窗口(session windows)</strong></p>
</div>
<div class="paragraph">
<p>会话窗口不可能重叠，并且会话窗口的大小也不是固定的。不活跃的时间长度定义了会话窗口的界限。不活跃的时间是指这段时间没有元素到达。下图展示了元素如何被分配到会话窗口。</p>
</div>
<div class="imageblock">
<div class="content">
<img src="images/spaf_0603.png" alt="spaf 0603">
</div>
</div>
<div class="listingblock">
<div class="content">
<pre class="pygments highlight"><code data-lang="scala"><span></span><span class="tok-k">val</span> <span class="tok-n">sessionWindows</span> <span class="tok-k">=</span> <span class="tok-n">sensorData</span>
  <span class="tok-o">.</span><span class="tok-n">keyBy</span><span class="tok-o">(</span><span class="tok-k">_</span><span class="tok-o">.</span><span class="tok-n">id</span><span class="tok-o">)</span>
  <span class="tok-o">.</span><span class="tok-n">window</span><span class="tok-o">(</span><span class="tok-nc">EventTimeSessionWindows</span><span class="tok-o">.</span><span class="tok-n">withGap</span><span class="tok-o">(</span><span class="tok-nc">Time</span><span class="tok-o">.</span><span class="tok-n">minutes</span><span class="tok-o">(</span><span class="tok-mi">15</span><span class="tok-o">)))</span>
  <span class="tok-o">.</span><span class="tok-n">process</span><span class="tok-o">(...)</span>

<span class="tok-k">val</span> <span class="tok-n">sessionWindows</span> <span class="tok-k">=</span> <span class="tok-n">sensorData</span>
  <span class="tok-o">.</span><span class="tok-n">keyBy</span><span class="tok-o">(</span><span class="tok-k">_</span><span class="tok-o">.</span><span class="tok-n">id</span><span class="tok-o">)</span>
  <span class="tok-o">.</span><span class="tok-n">window</span><span class="tok-o">(</span><span class="tok-nc">ProcessingTimeSessionWindows</span><span class="tok-o">.</span><span class="tok-n">withGap</span><span class="tok-o">(</span><span class="tok-nc">Time</span><span class="tok-o">.</span><span class="tok-n">minutes</span><span class="tok-o">(</span><span class="tok-mi">15</span><span class="tok-o">)))</span>
  <span class="tok-o">.</span><span class="tok-n">process</span><span class="tok-o">(...)</span></code></pre>
</div>
</div>
<div class="paragraph">
<p>由于会话窗口的开始时间和结束时间取决于接收到的元素，所以窗口分配器无法立即将所有的元素分配到正确的窗口中去。相反，会话窗口分配器最开始时先将每一个元素分配到它自己独有的窗口中去，窗口开始时间是这个元素的时间戳，窗口大小是session gap的大小。接下来，会话窗口分配器会将出现重叠的窗口合并成一个窗口。</p>
</div>
</div>
<div class="sect3">
<h4 id="_调用窗口计算函数">6.3.3. 调用窗口计算函数</h4>
<div class="paragraph">
<p>window functions定义了窗口中数据的计算逻辑。有两种计算逻辑：</p>
</div>
<div class="olist arabic">
<ol class="arabic">
<li>
<p>增量聚合函数(Incremental aggregation functions)：当一个事件被添加到窗口时，触发函数计算，并且更新window的状态(单个值)。最终聚合的结果将作为输出。ReduceFunction和AggregateFunction是增量聚合函数。</p>
</li>
<li>
<p>全窗口函数(Full window functions)：这个函数将会收集窗口中所有的元素，可以做一些复杂计算。ProcessWindowFunction是window function。</p>
</li>
</ol>
</div>
<div class="paragraph">
<p><strong>ReduceFunction</strong></p>
</div>
<div class="paragraph">
<p>例子: 计算每个传感器15s窗口中的温度最小值</p>
</div>
<div class="listingblock">
<div class="title">Example 6-10</div>
<div class="content">
<pre class="pygments highlight"><code data-lang="scala"><span></span><span class="tok-k">val</span> <span class="tok-n">minTempPerWindow</span><span class="tok-k">:</span> <span class="tok-kt">DataStream</span><span class="tok-o">[(</span><span class="tok-kt">String</span>, <span class="tok-kt">Double</span><span class="tok-o">)]</span> <span class="tok-k">=</span> <span class="tok-n">sensorData</span>
  <span class="tok-o">.</span><span class="tok-n">map</span><span class="tok-o">(</span><span class="tok-n">r</span> <span class="tok-k">=&gt;</span> <span class="tok-o">(</span><span class="tok-n">r</span><span class="tok-o">.</span><span class="tok-n">id</span><span class="tok-o">,</span> <span class="tok-n">r</span><span class="tok-o">.</span><span class="tok-n">temperature</span><span class="tok-o">))</span>
  <span class="tok-o">.</span><span class="tok-n">keyBy</span><span class="tok-o">(</span><span class="tok-k">_</span><span class="tok-o">.</span><span class="tok-n">_1</span><span class="tok-o">)</span>
  <span class="tok-o">.</span><span class="tok-n">timeWindow</span><span class="tok-o">(</span><span class="tok-nc">Time</span><span class="tok-o">.</span><span class="tok-n">seconds</span><span class="tok-o">(</span><span class="tok-mi">15</span><span class="tok-o">))</span>
  <span class="tok-o">.</span><span class="tok-n">reduce</span><span class="tok-o">((</span><span class="tok-n">r1</span><span class="tok-o">,</span> <span class="tok-n">r2</span><span class="tok-o">)</span> <span class="tok-k">=&gt;</span> <span class="tok-o">(</span><span class="tok-n">r1</span><span class="tok-o">.</span><span class="tok-n">_1</span><span class="tok-o">,</span> <span class="tok-n">r1</span><span class="tok-o">.</span><span class="tok-n">_2</span><span class="tok-o">.</span><span class="tok-n">min</span><span class="tok-o">(</span><span class="tok-n">r2</span><span class="tok-o">.</span><span class="tok-n">_2</span><span class="tok-o">)))</span></code></pre>
</div>
</div>
<div class="paragraph">
<p><strong>AggregateFunction</strong></p>
</div>
<div class="paragraph">
<p>先来看接口定义</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="pygments highlight"><code data-lang="java"><span></span><span class="tok-kd">public</span> <span class="tok-kd">interface</span> <span class="tok-nc">AggregateFunction</span><span class="tok-o">&lt;</span><span class="tok-n">IN</span><span class="tok-o">,</span> <span class="tok-n">ACC</span><span class="tok-o">,</span> <span class="tok-n">OUT</span><span class="tok-o">&gt;</span> <span class="tok-kd">extends</span> <span class="tok-n">Function</span><span class="tok-o">,</span> <span class="tok-n">Serializable</span> <span class="tok-o">{</span>

  <span class="tok-c1">// create a new accumulator to start a new aggregate</span>
  <span class="tok-n">ACC</span> <span class="tok-nf">createAccumulator</span><span class="tok-o">();</span>

  <span class="tok-c1">// add an input element to the accumulator and return the accumulator</span>
  <span class="tok-n">ACC</span> <span class="tok-nf">add</span><span class="tok-o">(</span><span class="tok-n">IN</span> <span class="tok-n">value</span><span class="tok-o">,</span> <span class="tok-n">ACC</span> <span class="tok-n">accumulator</span><span class="tok-o">);</span>

  <span class="tok-c1">// compute the result from the accumulator and return it.</span>
  <span class="tok-n">OUT</span> <span class="tok-nf">getResult</span><span class="tok-o">(</span><span class="tok-n">ACC</span> <span class="tok-n">accumulator</span><span class="tok-o">);</span>

  <span class="tok-c1">// merge two accumulators and return the result.</span>
  <span class="tok-n">ACC</span> <span class="tok-nf">merge</span><span class="tok-o">(</span><span class="tok-n">ACC</span> <span class="tok-n">a</span><span class="tok-o">,</span> <span class="tok-n">ACC</span> <span class="tok-n">b</span><span class="tok-o">);</span>
<span class="tok-o">}</span></code></pre>
</div>
</div>
<div class="paragraph">
<p>IN是输入元素的类型，ACC是累加器的类型，OUT是输出元素的类型。</p>
</div>
<div class="paragraph">
<p>例子</p>
</div>
<div class="listingblock">
<div class="title">Example 6-11</div>
<div class="content">
<pre class="pygments highlight"><code data-lang="scala"><span></span><span class="tok-k">val</span> <span class="tok-n">avgTempPerWindow</span><span class="tok-k">:</span> <span class="tok-kt">DataStream</span><span class="tok-o">[(</span><span class="tok-kt">String</span>, <span class="tok-kt">Double</span><span class="tok-o">)]</span> <span class="tok-k">=</span> <span class="tok-n">sensorData</span>
  <span class="tok-o">.</span><span class="tok-n">map</span><span class="tok-o">(</span><span class="tok-n">r</span> <span class="tok-k">=&gt;</span> <span class="tok-o">(</span><span class="tok-n">r</span><span class="tok-o">.</span><span class="tok-n">id</span><span class="tok-o">,</span> <span class="tok-n">r</span><span class="tok-o">.</span><span class="tok-n">temperature</span><span class="tok-o">))</span>
  <span class="tok-o">.</span><span class="tok-n">keyBy</span><span class="tok-o">(</span><span class="tok-k">_</span><span class="tok-o">.</span><span class="tok-n">_1</span><span class="tok-o">)</span>
  <span class="tok-o">.</span><span class="tok-n">timeWindow</span><span class="tok-o">(</span><span class="tok-nc">Time</span><span class="tok-o">.</span><span class="tok-n">seconds</span><span class="tok-o">(</span><span class="tok-mi">15</span><span class="tok-o">))</span>
  <span class="tok-o">.</span><span class="tok-n">aggregate</span><span class="tok-o">(</span><span class="tok-k">new</span> <span class="tok-nc">AvgTempFunction</span><span class="tok-o">)</span>

<span class="tok-c1">// An AggregateFunction to compute the average temperature per sensor.</span>
<span class="tok-c1">// The accumulator holds the sum of temperatures and an event count.</span>
<span class="tok-k">class</span> <span class="tok-nc">AvgTempFunction</span> <span class="tok-k">extends</span> <span class="tok-nc">AggregateFunction</span><span class="tok-o">[(</span><span class="tok-kt">String</span>, <span class="tok-kt">Double</span><span class="tok-o">)</span>, <span class="tok-o">(</span><span class="tok-kt">String</span>, <span class="tok-kt">Double</span>, <span class="tok-kt">Int</span><span class="tok-o">)</span>, <span class="tok-o">(</span><span class="tok-kt">String</span>, <span class="tok-kt">Double</span><span class="tok-o">)]</span> <span class="tok-o">{</span>

  <span class="tok-k">override</span> <span class="tok-k">def</span> <span class="tok-n">createAccumulator</span><span class="tok-o">()</span> <span class="tok-k">=</span> <span class="tok-o">{</span>
    <span class="tok-o">(</span><span class="tok-s">&quot;&quot;</span><span class="tok-o">,</span> <span class="tok-mf">0.0</span><span class="tok-o">,</span> <span class="tok-mi">0</span><span class="tok-o">)</span>
  <span class="tok-o">}</span>

  <span class="tok-k">override</span> <span class="tok-k">def</span> <span class="tok-n">add</span><span class="tok-o">(</span><span class="tok-n">in</span><span class="tok-k">:</span> <span class="tok-o">(</span><span class="tok-kt">String</span><span class="tok-o">,</span> <span class="tok-kt">Double</span><span class="tok-o">),</span> <span class="tok-n">acc</span><span class="tok-k">:</span> <span class="tok-o">(</span><span class="tok-kt">String</span><span class="tok-o">,</span> <span class="tok-kt">Double</span><span class="tok-o">,</span> <span class="tok-nc">Int</span><span class="tok-o">))</span> <span class="tok-k">=</span> <span class="tok-o">{</span>
    <span class="tok-o">(</span><span class="tok-n">in</span><span class="tok-o">.</span><span class="tok-n">_1</span><span class="tok-o">,</span> <span class="tok-n">in</span><span class="tok-o">.</span><span class="tok-n">_2</span> <span class="tok-o">+</span> <span class="tok-n">acc</span><span class="tok-o">.</span><span class="tok-n">_2</span><span class="tok-o">,</span> <span class="tok-mi">1</span> <span class="tok-o">+</span> <span class="tok-n">acc</span><span class="tok-o">.</span><span class="tok-n">_3</span><span class="tok-o">)</span>
  <span class="tok-o">}</span>

  <span class="tok-k">override</span> <span class="tok-k">def</span> <span class="tok-n">getResult</span><span class="tok-o">(</span><span class="tok-n">acc</span><span class="tok-k">:</span> <span class="tok-o">(</span><span class="tok-kt">String</span><span class="tok-o">,</span> <span class="tok-kt">Double</span><span class="tok-o">,</span> <span class="tok-nc">Int</span><span class="tok-o">))</span> <span class="tok-k">=</span> <span class="tok-o">{</span>
    <span class="tok-o">(</span><span class="tok-n">acc</span><span class="tok-o">.</span><span class="tok-n">_1</span><span class="tok-o">,</span> <span class="tok-n">acc</span><span class="tok-o">.</span><span class="tok-n">_2</span> <span class="tok-o">/</span> <span class="tok-n">acc</span><span class="tok-o">.</span><span class="tok-n">_3</span><span class="tok-o">)</span>
  <span class="tok-o">}</span>

  <span class="tok-k">override</span> <span class="tok-k">def</span> <span class="tok-n">merge</span><span class="tok-o">(</span><span class="tok-n">acc1</span><span class="tok-k">:</span> <span class="tok-o">(</span><span class="tok-kt">String</span><span class="tok-o">,</span> <span class="tok-kt">Double</span><span class="tok-o">,</span> <span class="tok-nc">Int</span><span class="tok-o">),</span> <span class="tok-n">acc2</span><span class="tok-k">:</span> <span class="tok-o">(</span><span class="tok-kt">String</span><span class="tok-o">,</span> <span class="tok-kt">Double</span><span class="tok-o">,</span> <span class="tok-nc">Int</span><span class="tok-o">))</span> <span class="tok-k">=</span> <span class="tok-o">{</span>
    <span class="tok-o">(</span><span class="tok-n">acc1</span><span class="tok-o">.</span><span class="tok-n">_1</span><span class="tok-o">,</span> <span class="tok-n">acc1</span><span class="tok-o">.</span><span class="tok-n">_2</span> <span class="tok-o">+</span> <span class="tok-n">acc2</span><span class="tok-o">.</span><span class="tok-n">_2</span><span class="tok-o">,</span> <span class="tok-n">acc1</span><span class="tok-o">.</span><span class="tok-n">_3</span> <span class="tok-o">+</span> <span class="tok-n">acc2</span><span class="tok-o">.</span><span class="tok-n">_3</span><span class="tok-o">)</span>
  <span class="tok-o">}</span>
<span class="tok-o">}</span></code></pre>
</div>
</div>
<div class="paragraph">
<p><strong>ProcessWindowFunction</strong></p>
</div>
<div class="paragraph">
<p>一些业务场景，我们需要收集窗口内所有的数据进行计算，例如计算窗口数据的中位数，或者计算窗口数据中出现频率最高的值。这样的需求，使用ReduceFunction和AggregateFunction就无法实现了。这个时候就需要ProcessWindowFunction了。</p>
</div>
<div class="paragraph">
<p>先来看接口定义</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="pygments highlight"><code data-lang="java"><span></span><span class="tok-kd">public</span> <span class="tok-kd">abstract</span> <span class="tok-kd">class</span> <span class="tok-nc">ProcessWindowFunction</span><span class="tok-o">&lt;</span><span class="tok-n">IN</span><span class="tok-o">,</span> <span class="tok-n">OUT</span><span class="tok-o">,</span> <span class="tok-n">KEY</span><span class="tok-o">,</span> <span class="tok-n">W</span> <span class="tok-kd">extends</span> <span class="tok-n">Window</span><span class="tok-o">&gt;</span> <span class="tok-kd">extends</span> <span class="tok-n">AbstractRichFunction</span> <span class="tok-o">{</span>

  <span class="tok-c1">// Evaluates the window</span>
  <span class="tok-kt">void</span> <span class="tok-nf">process</span><span class="tok-o">(</span><span class="tok-n">KEY</span> <span class="tok-n">key</span><span class="tok-o">,</span> <span class="tok-n">Context</span> <span class="tok-n">ctx</span><span class="tok-o">,</span> <span class="tok-n">Iterable</span><span class="tok-o">&lt;</span><span class="tok-n">IN</span><span class="tok-o">&gt;</span> <span class="tok-n">vals</span><span class="tok-o">,</span> <span class="tok-n">Collector</span><span class="tok-o">&lt;</span><span class="tok-n">OUT</span><span class="tok-o">&gt;</span> <span class="tok-n">out</span><span class="tok-o">)</span> <span class="tok-kd">throws</span> <span class="tok-n">Exception</span><span class="tok-o">;</span>

  <span class="tok-c1">// Deletes any custom per-window state when the window is purged</span>
  <span class="tok-kd">public</span> <span class="tok-kt">void</span> <span class="tok-nf">clear</span><span class="tok-o">(</span><span class="tok-n">Context</span> <span class="tok-n">ctx</span><span class="tok-o">)</span> <span class="tok-kd">throws</span> <span class="tok-n">Exception</span> <span class="tok-o">{}</span>

  <span class="tok-c1">// The context holding window metadata</span>
  <span class="tok-kd">public</span> <span class="tok-kd">abstract</span> <span class="tok-kd">class</span> <span class="tok-nc">Context</span> <span class="tok-kd">implements</span> <span class="tok-n">Serializable</span> <span class="tok-o">{</span>
    <span class="tok-c1">// Returns the metadata of the window</span>
    <span class="tok-kd">public</span> <span class="tok-kd">abstract</span> <span class="tok-n">W</span> <span class="tok-nf">window</span><span class="tok-o">();</span>

    <span class="tok-c1">// Returns the current processing time</span>
    <span class="tok-kd">public</span> <span class="tok-kd">abstract</span> <span class="tok-kt">long</span> <span class="tok-nf">currentProcessingTime</span><span class="tok-o">();</span>

    <span class="tok-c1">// Returns the current event-time watermark</span>
    <span class="tok-kd">public</span> <span class="tok-kd">abstract</span> <span class="tok-kt">long</span> <span class="tok-nf">currentWatermark</span><span class="tok-o">();</span>

    <span class="tok-c1">// State accessor for per-window state</span>
    <span class="tok-kd">public</span> <span class="tok-kd">abstract</span> <span class="tok-n">KeyedStateStore</span> <span class="tok-nf">windowState</span><span class="tok-o">();</span>

    <span class="tok-c1">// State accessor for per-key global state</span>
    <span class="tok-kd">public</span> <span class="tok-kd">abstract</span> <span class="tok-n">KeyedStateStore</span> <span class="tok-nf">globalState</span><span class="tok-o">();</span>

    <span class="tok-c1">// Emits a record to the side output identified by the OutputTag.</span>
    <span class="tok-kd">public</span> <span class="tok-kd">abstract</span> <span class="tok-o">&lt;</span><span class="tok-n">X</span><span class="tok-o">&gt;</span> <span class="tok-kt">void</span> <span class="tok-nf">output</span><span class="tok-o">(</span><span class="tok-n">OutputTag</span><span class="tok-o">&lt;</span><span class="tok-n">X</span><span class="tok-o">&gt;</span> <span class="tok-n">outputTag</span><span class="tok-o">,</span> <span class="tok-n">X</span> <span class="tok-n">value</span><span class="tok-o">);</span>
  <span class="tok-o">}</span>
<span class="tok-o">}</span></code></pre>
</div>
</div>
<div class="paragraph">
<p>process()方法接受的参数为：window的key，Iterable迭代器包含窗口的所有元素，Collector用于输出结果流。Context参数和别的process方法一样。而ProcessWindowFunction的Context对象还可以访问window的元数据(窗口开始和结束时间)，当前处理时间和水位线，per-window state和per-key global state，side outputs。</p>
</div>
<div class="ulist">
<ul>
<li>
<p>per-window state: 用于保存一些信息，这些信息可以被process()访问，只要process所处理的元素属于这个窗口。</p>
</li>
<li>
<p>per-key global state: 同一个key，也就是在一条KeyedStream上，不同的window可以访问per-key global state保存的值。</p>
</li>
</ul>
</div>
<div class="paragraph">
<p>例子：计算5s滚动窗口中的最低和最高的温度。输出的元素包含了(流的Key, 最低温度, 最高温度, 窗口结束时间)。</p>
</div>
<div class="listingblock">
<div class="title">Example 6-12</div>
<div class="content">
<pre class="pygments highlight"><code data-lang="scala"><span></span><span class="tok-k">val</span> <span class="tok-n">minMaxTempPerWindow</span><span class="tok-k">:</span> <span class="tok-kt">DataStream</span><span class="tok-o">[</span><span class="tok-kt">MinMaxTemp</span><span class="tok-o">]</span> <span class="tok-k">=</span> <span class="tok-n">sensorData</span>
  <span class="tok-o">.</span><span class="tok-n">keyBy</span><span class="tok-o">(</span><span class="tok-k">_</span><span class="tok-o">.</span><span class="tok-n">id</span><span class="tok-o">)</span>
  <span class="tok-o">.</span><span class="tok-n">timeWindow</span><span class="tok-o">(</span><span class="tok-nc">Time</span><span class="tok-o">.</span><span class="tok-n">seconds</span><span class="tok-o">(</span><span class="tok-mi">5</span><span class="tok-o">))</span>
  <span class="tok-o">.</span><span class="tok-n">process</span><span class="tok-o">(</span><span class="tok-k">new</span> <span class="tok-nc">HighAndLowTempProcessFunction</span><span class="tok-o">)</span>

<span class="tok-k">case</span> <span class="tok-k">class</span> <span class="tok-nc">MinMaxTemp</span><span class="tok-o">(</span><span class="tok-n">id</span><span class="tok-k">:</span> <span class="tok-kt">String</span><span class="tok-o">,</span> <span class="tok-n">min</span><span class="tok-k">:</span> <span class="tok-kt">Double</span><span class="tok-o">,</span> <span class="tok-n">max</span><span class="tok-k">:</span> <span class="tok-kt">Double</span><span class="tok-o">,</span> <span class="tok-n">endTs</span><span class="tok-k">:</span> <span class="tok-kt">Long</span><span class="tok-o">)</span>

<span class="tok-k">class</span> <span class="tok-nc">HighAndLowTempProcessFunction</span> <span class="tok-k">extends</span> <span class="tok-nc">ProcessWindowFunction</span><span class="tok-o">[</span><span class="tok-kt">SensorReading</span>, <span class="tok-kt">MinMaxTemp</span>, <span class="tok-kt">String</span>, <span class="tok-kt">TimeWindow</span><span class="tok-o">]</span> <span class="tok-o">{</span>
  <span class="tok-k">override</span> <span class="tok-k">def</span> <span class="tok-n">process</span><span class="tok-o">(</span><span class="tok-n">key</span><span class="tok-k">:</span> <span class="tok-kt">String</span><span class="tok-o">,</span>
                       <span class="tok-n">ctx</span><span class="tok-k">:</span> <span class="tok-kt">Context</span><span class="tok-o">,</span>
                       <span class="tok-n">vals</span><span class="tok-k">:</span> <span class="tok-kt">Iterable</span><span class="tok-o">[</span><span class="tok-kt">SensorReading</span><span class="tok-o">],</span>
                       <span class="tok-n">out</span><span class="tok-k">:</span> <span class="tok-kt">Collector</span><span class="tok-o">[</span><span class="tok-kt">MinMaxTemp</span><span class="tok-o">])</span><span class="tok-k">:</span> <span class="tok-kt">Unit</span> <span class="tok-o">=</span> <span class="tok-o">{</span>
    <span class="tok-k">val</span> <span class="tok-n">temps</span> <span class="tok-k">=</span> <span class="tok-n">vals</span><span class="tok-o">.</span><span class="tok-n">map</span><span class="tok-o">(</span><span class="tok-k">_</span><span class="tok-o">.</span><span class="tok-n">temperature</span><span class="tok-o">)</span>
    <span class="tok-k">val</span> <span class="tok-n">windowEnd</span> <span class="tok-k">=</span> <span class="tok-n">ctx</span><span class="tok-o">.</span><span class="tok-n">window</span><span class="tok-o">.</span><span class="tok-n">getEnd</span>

    <span class="tok-n">out</span><span class="tok-o">.</span><span class="tok-n">collect</span><span class="tok-o">(</span><span class="tok-nc">MinMaxTemp</span><span class="tok-o">(</span><span class="tok-n">key</span><span class="tok-o">,</span> <span class="tok-n">temps</span><span class="tok-o">.</span><span class="tok-n">min</span><span class="tok-o">,</span> <span class="tok-n">temps</span><span class="tok-o">.</span><span class="tok-n">max</span><span class="tok-o">,</span> <span class="tok-n">windowEnd</span><span class="tok-o">))</span>
  <span class="tok-o">}</span>
<span class="tok-o">}</span></code></pre>
</div>
</div>
<div class="paragraph">
<p>我们还可以将ReduceFunction/AggregateFunction和ProcessWindowFunction结合起来使用。ReduceFunction/AggregateFunction做增量聚合，ProcessWindowFunction提供更多的对数据流的访问权限。如果只使用ProcessWindowFunction(底层的实现为将事件都保存在ListState中)，将会非常占用空间。分配到某个窗口的元素将被提前聚合，而当窗口的trigger触发时，也就是窗口收集完数据关闭时，将会把聚合结果发送到ProcessWindowFunction中，这时Iterable参数将会只有一个值，就是前面聚合的值。</p>
</div>
<div class="paragraph">
<p>例子</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="pygments highlight"><code data-lang="scala"><span></span><span class="tok-n">input</span>
  <span class="tok-o">.</span><span class="tok-n">keyBy</span><span class="tok-o">(...)</span>
  <span class="tok-o">.</span><span class="tok-n">timeWindow</span><span class="tok-o">(...)</span>
  <span class="tok-o">.</span><span class="tok-n">reduce</span><span class="tok-o">(</span>
    <span class="tok-n">incrAggregator</span><span class="tok-k">:</span> <span class="tok-kt">ReduceFunction</span><span class="tok-o">[</span><span class="tok-kt">IN</span><span class="tok-o">],</span>
    <span class="tok-n">function</span><span class="tok-k">:</span> <span class="tok-kt">ProcessWindowFunction</span><span class="tok-o">[</span><span class="tok-kt">IN</span>, <span class="tok-kt">OUT</span>, <span class="tok-kt">K</span>, <span class="tok-kt">W</span><span class="tok-o">])</span>

<span class="tok-n">input</span>
  <span class="tok-o">.</span><span class="tok-n">keyBy</span><span class="tok-o">(...)</span>
  <span class="tok-o">.</span><span class="tok-n">timeWindow</span><span class="tok-o">(...)</span>
  <span class="tok-o">.</span><span class="tok-n">aggregate</span><span class="tok-o">(</span>
    <span class="tok-n">incrAggregator</span><span class="tok-k">:</span> <span class="tok-kt">AggregateFunction</span><span class="tok-o">[</span><span class="tok-kt">IN</span>, <span class="tok-kt">ACC</span>, <span class="tok-kt">V</span><span class="tok-o">],</span>
    <span class="tok-n">windowFunction</span><span class="tok-k">:</span> <span class="tok-kt">ProcessWindowFunction</span><span class="tok-o">[</span><span class="tok-kt">V</span>, <span class="tok-kt">OUT</span>, <span class="tok-kt">K</span>, <span class="tok-kt">W</span><span class="tok-o">])</span></code></pre>
</div>
</div>
<div class="paragraph">
<p>我们把之前的需求重新使用以上两种方法实现一下。</p>
</div>
<div class="listingblock">
<div class="title">Example 6-13</div>
<div class="content">
<pre class="pygments highlight"><code data-lang="scala"><span></span><span class="tok-k">case</span> <span class="tok-k">class</span> <span class="tok-nc">MinMaxTemp</span><span class="tok-o">(</span><span class="tok-n">id</span><span class="tok-k">:</span> <span class="tok-kt">String</span><span class="tok-o">,</span> <span class="tok-n">min</span><span class="tok-k">:</span> <span class="tok-kt">Double</span><span class="tok-o">,</span> <span class="tok-n">max</span><span class="tok-k">:</span> <span class="tok-kt">Double</span><span class="tok-o">,</span> <span class="tok-n">endTs</span><span class="tok-k">:</span> <span class="tok-kt">Long</span><span class="tok-o">)</span>

<span class="tok-k">val</span> <span class="tok-n">minMaxTempPerWindow2</span><span class="tok-k">:</span> <span class="tok-kt">DataStream</span><span class="tok-o">[</span><span class="tok-kt">MinMaxTemp</span><span class="tok-o">]</span> <span class="tok-k">=</span> <span class="tok-n">sensorData</span>
  <span class="tok-o">.</span><span class="tok-n">map</span><span class="tok-o">(</span><span class="tok-n">r</span> <span class="tok-k">=&gt;</span> <span class="tok-o">(</span><span class="tok-n">r</span><span class="tok-o">.</span><span class="tok-n">id</span><span class="tok-o">,</span> <span class="tok-n">r</span><span class="tok-o">.</span><span class="tok-n">temperature</span><span class="tok-o">,</span> <span class="tok-n">r</span><span class="tok-o">.</span><span class="tok-n">temperature</span><span class="tok-o">))</span>
  <span class="tok-o">.</span><span class="tok-n">keyBy</span><span class="tok-o">(</span><span class="tok-k">_</span><span class="tok-o">.</span><span class="tok-n">_1</span><span class="tok-o">)</span>
  <span class="tok-o">.</span><span class="tok-n">timeWindow</span><span class="tok-o">(</span><span class="tok-nc">Time</span><span class="tok-o">.</span><span class="tok-n">seconds</span><span class="tok-o">(</span><span class="tok-mi">5</span><span class="tok-o">))</span>
  <span class="tok-o">.</span><span class="tok-n">reduce</span><span class="tok-o">(</span>
    <span class="tok-o">(</span><span class="tok-n">r1</span><span class="tok-k">:</span> <span class="tok-o">(</span><span class="tok-kt">String</span><span class="tok-o">,</span> <span class="tok-kt">Double</span><span class="tok-o">,</span> <span class="tok-nc">Double</span><span class="tok-o">),</span> <span class="tok-n">r2</span><span class="tok-k">:</span> <span class="tok-o">(</span><span class="tok-kt">String</span><span class="tok-o">,</span> <span class="tok-kt">Double</span><span class="tok-o">,</span> <span class="tok-nc">Double</span><span class="tok-o">))</span> <span class="tok-k">=&gt;</span> <span class="tok-o">{</span>
      <span class="tok-o">(</span><span class="tok-n">r1</span><span class="tok-o">.</span><span class="tok-n">_1</span><span class="tok-o">,</span> <span class="tok-n">r1</span><span class="tok-o">.</span><span class="tok-n">_2</span><span class="tok-o">.</span><span class="tok-n">min</span><span class="tok-o">(</span><span class="tok-n">r2</span><span class="tok-o">.</span><span class="tok-n">_2</span><span class="tok-o">),</span> <span class="tok-n">r1</span><span class="tok-o">.</span><span class="tok-n">_3</span><span class="tok-o">.</span><span class="tok-n">max</span><span class="tok-o">(</span><span class="tok-n">r2</span><span class="tok-o">.</span><span class="tok-n">_3</span><span class="tok-o">))</span>
    <span class="tok-o">},</span>
    <span class="tok-k">new</span> <span class="tok-nc">AssignWindowEndProcessFunction</span><span class="tok-o">()</span>
  <span class="tok-o">)</span>

<span class="tok-k">class</span> <span class="tok-nc">AssignWindowEndProcessFunction</span> <span class="tok-k">extends</span> <span class="tok-nc">ProcessWindowFunction</span><span class="tok-o">[(</span><span class="tok-kt">String</span>, <span class="tok-kt">Double</span>, <span class="tok-kt">Double</span><span class="tok-o">)</span>, <span class="tok-kt">MinMaxTemp</span>, <span class="tok-kt">String</span>, <span class="tok-kt">TimeWindow</span><span class="tok-o">]</span> <span class="tok-o">{</span>
  <span class="tok-k">override</span> <span class="tok-k">def</span> <span class="tok-n">process</span><span class="tok-o">(</span><span class="tok-n">key</span><span class="tok-k">:</span> <span class="tok-kt">String</span><span class="tok-o">,</span>
                       <span class="tok-n">ctx</span><span class="tok-k">:</span> <span class="tok-kt">Context</span><span class="tok-o">,</span>
                       <span class="tok-n">minMaxIt</span><span class="tok-k">:</span> <span class="tok-kt">Iterable</span><span class="tok-o">[(</span><span class="tok-kt">String</span>, <span class="tok-kt">Double</span>, <span class="tok-kt">Double</span><span class="tok-o">)],</span>
                       <span class="tok-n">out</span><span class="tok-k">:</span> <span class="tok-kt">Collector</span><span class="tok-o">[</span><span class="tok-kt">MinMaxTemp</span><span class="tok-o">])</span><span class="tok-k">:</span> <span class="tok-kt">Unit</span> <span class="tok-o">=</span> <span class="tok-o">{</span>
    <span class="tok-k">val</span> <span class="tok-n">minMax</span> <span class="tok-k">=</span> <span class="tok-n">minMaxIt</span><span class="tok-o">.</span><span class="tok-n">head</span>
    <span class="tok-k">val</span> <span class="tok-n">windowEnd</span> <span class="tok-k">=</span> <span class="tok-n">ctx</span><span class="tok-o">.</span><span class="tok-n">window</span><span class="tok-o">.</span><span class="tok-n">getEnd</span>
    <span class="tok-n">out</span><span class="tok-o">.</span><span class="tok-n">collect</span><span class="tok-o">(</span><span class="tok-nc">MinMaxTemp</span><span class="tok-o">(</span><span class="tok-n">key</span><span class="tok-o">,</span> <span class="tok-n">minMax</span><span class="tok-o">.</span><span class="tok-n">_2</span><span class="tok-o">,</span> <span class="tok-n">minMax</span><span class="tok-o">.</span><span class="tok-n">_3</span><span class="tok-o">,</span> <span class="tok-n">windowEnd</span><span class="tok-o">))</span>
  <span class="tok-o">}</span>
<span class="tok-o">}</span></code></pre>
</div>
</div>
</div>
<div class="sect3">
<h4 id="_自定义窗口操作符windows_operators">6.3.4. 自定义窗口操作符(windows operators)</h4>
<div class="paragraph">
<p>Flink内置的window operators分配器已经已经足够应付大多数应用场景。尽管如此，如果我们需要实现一些复杂的窗口逻辑，例如：可以发射早到的事件或者碰到迟到的事件就更新窗口的结果，或者窗口的开始和结束决定于特定事件的接收。</p>
</div>
<div class="paragraph">
<p>DataStream API暴露了接口和方法来自定义窗口操作符。</p>
</div>
<div class="ulist">
<ul>
<li>
<p>自定义窗口分配器</p>
</li>
<li>
<p>自定义窗口计算触发器(trigger)</p>
</li>
<li>
<p>自定义窗口数据清理功能(evictor)</p>
</li>
</ul>
</div>
<div class="paragraph">
<p>当一个事件来到窗口操作符，首先将会传给WindowAssigner来处理。WindowAssigner决定了事件将被分配到哪些窗口。如果窗口不存在，WindowAssigner将会创建一个新的窗口。</p>
</div>
<div class="paragraph">
<p>如果一个window operator接受了一个增量聚合函数作为参数，例如ReduceFunction或者AggregateFunction，新到的元素将会立即被聚合，而聚合结果result将存储在window中。如果window operator没有使用增量聚合函数，那么新元素将被添加到ListState中，ListState中保存了所有分配给窗口的元素。</p>
</div>
<div class="paragraph">
<p>新元素被添加到窗口时，这个新元素同时也被传给了window的trigger。trigger定义了window何时准备好求值，何时window被清空。trigger可以基于window被分配的元素和注册的定时器来对窗口的所有元素求值或者在特定事件清空window中所有的元素。</p>
</div>
<div class="paragraph">
<p>当window operator只接收一个增量聚合函数作为参数时：</p>
</div>
<div class="paragraph">
<p>当window operator只接收一个全窗口函数作为参数时：</p>
</div>
<div class="paragraph">
<p>当window operator接收一个增量聚合函数和一个全窗口函数作为参数时：</p>
</div>
<div class="paragraph">
<p>evictor是一个可选的组件，可以被注入到ProcessWindowFunction之前或者之后调用。evictor可以清除掉window中收集的元素。由于evictor需要迭代所有的元素，所以evictor只能使用在没有增量聚合函数作为参数的情况下。</p>
</div>
<div class="paragraph">
<p>下面的代码说明了如果使用自定义的trigger和evictor定义一个window operator：</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="pygments highlight"><code data-lang="scala"><span></span><span class="tok-n">stream</span>
  <span class="tok-o">.</span><span class="tok-n">keyBy</span><span class="tok-o">(...)</span>
  <span class="tok-o">.</span><span class="tok-n">window</span><span class="tok-o">(...)</span>
 <span class="tok-o">[</span><span class="tok-kt">.trigger</span><span class="tok-o">(</span><span class="tok-kt">...</span><span class="tok-o">)]</span>
 <span class="tok-o">[</span><span class="tok-kt">.evictor</span><span class="tok-o">(</span><span class="tok-kt">...</span><span class="tok-o">)]</span>
  <span class="tok-o">.</span><span class="tok-n">reduce</span><span class="tok-o">/</span><span class="tok-n">aggregate</span><span class="tok-o">/</span><span class="tok-n">process</span><span class="tok-o">(...)</span></code></pre>
</div>
</div>
<div class="paragraph">
<p>注意：每个WindowAssigner都有一个默认的trigger。</p>
</div>
<div class="paragraph">
<p><strong>窗口生命周期</strong></p>
</div>
<div class="paragraph">
<p>当WindowAssigner分配某个窗口的第一个元素时，这个窗口才会被创建。所以不存在没有元素的窗口。</p>
</div>
<div class="paragraph">
<p>一个窗口包含了如下状态：</p>
</div>
<div class="ulist">
<ul>
<li>
<p>Window content</p>
<div class="ulist">
<ul>
<li>
<p>分配到这个窗口的元素</p>
</li>
<li>
<p>增量聚合的结果(如果window operator接收了ReduceFunction或者AggregateFunction作为参数)。</p>
</li>
</ul>
</div>
</li>
<li>
<p>Window object</p>
<div class="ulist">
<ul>
<li>
<p>WindowAssigner返回0个，1个或者多个window object。</p>
</li>
<li>
<p>window operator根据返回的window object来聚合元素。</p>
</li>
<li>
<p>每一个window object包含一个windowEnd时间戳，来区别于其他窗口。</p>
</li>
</ul>
</div>
</li>
<li>
<p>触发器的定时器：一个触发器可以注册定时事件，到了定时的时间可以执行相应的回调函数，例如：对窗口进行求值或者清空窗口。</p>
</li>
<li>
<p>触发器中的自定义状态：触发器可以定义和使用自定义的、per-window或者per-key状态。这个状态完全被触发器所控制。而不是被window operator控制。</p>
</li>
</ul>
</div>
<div class="paragraph">
<p>当窗口结束时间来到，window operator将删掉这个窗口。窗口结束时间是由window object的end timestamp所定义的。无论是使用processing time还是event time，窗口结束时间是什么类型可以调用WindowAssigner.isEventTime()方法获得。</p>
</div>
<div class="paragraph">
<p><strong>窗口分配器(window assigners)</strong></p>
</div>
<div class="paragraph">
<p>WindowAssigner将会把元素分配到0个，1个或者多个窗口中去。我们看一下WindowAssigner接口：</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="pygments highlight"><code data-lang="java"><span></span><span class="tok-kd">public</span> <span class="tok-kd">abstract</span> <span class="tok-kd">class</span> <span class="tok-nc">WindowAssigner</span><span class="tok-o">&lt;</span><span class="tok-n">T</span><span class="tok-o">,</span> <span class="tok-n">W</span> <span class="tok-kd">extends</span> <span class="tok-n">Window</span><span class="tok-o">&gt;</span>
    <span class="tok-kd">implements</span> <span class="tok-n">Serializable</span> <span class="tok-o">{</span>

  <span class="tok-kd">public</span> <span class="tok-kd">abstract</span> <span class="tok-n">Collection</span><span class="tok-o">&lt;</span><span class="tok-n">W</span><span class="tok-o">&gt;</span> <span class="tok-nf">assignWindows</span><span class="tok-o">(</span>
    <span class="tok-n">T</span> <span class="tok-n">element</span><span class="tok-o">,</span>
    <span class="tok-kt">long</span> <span class="tok-n">timestamp</span><span class="tok-o">,</span>
    <span class="tok-n">WindowAssignerContext</span> <span class="tok-n">context</span><span class="tok-o">);</span>

  <span class="tok-kd">public</span> <span class="tok-kd">abstract</span> <span class="tok-n">Trigger</span><span class="tok-o">&lt;</span><span class="tok-n">T</span><span class="tok-o">,</span> <span class="tok-n">W</span><span class="tok-o">&gt;</span> <span class="tok-nf">getDefaultTriger</span><span class="tok-o">(</span>
    <span class="tok-n">StreamExecutionEnvironment</span> <span class="tok-n">env</span><span class="tok-o">);</span>

  <span class="tok-kd">public</span> <span class="tok-kd">abstract</span> <span class="tok-n">TypeSerializer</span><span class="tok-o">&lt;</span><span class="tok-n">W</span><span class="tok-o">&gt;</span> <span class="tok-nf">getWindowSerializer</span><span class="tok-o">(</span>
    <span class="tok-n">ExecutionConfig</span> <span class="tok-n">executionConfig</span><span class="tok-o">);</span>

  <span class="tok-kd">public</span> <span class="tok-kd">abstract</span> <span class="tok-kt">boolean</span> <span class="tok-nf">isEventTime</span><span class="tok-o">();</span>

  <span class="tok-kd">public</span> <span class="tok-kd">abstract</span> <span class="tok-kd">static</span> <span class="tok-kd">class</span> <span class="tok-nc">WindowAssignerContext</span> <span class="tok-o">{</span>
    <span class="tok-kd">public</span> <span class="tok-kd">abstract</span> <span class="tok-kt">long</span> <span class="tok-nf">getCurrentProcessingTime</span><span class="tok-o">();</span>
  <span class="tok-o">}</span>
<span class="tok-o">}</span></code></pre>
</div>
</div>
<div class="paragraph">
<p>WindowAssigner有两个泛型参数：</p>
</div>
<div class="ulist">
<ul>
<li>
<p>T: 事件的数据类型</p>
</li>
<li>
<p>W: 窗口的类型</p>
</li>
</ul>
</div>
<div class="paragraph">
<p>下面的代码创建了一个自定义窗口分配器，是一个30秒的滚动事件时间窗口。</p>
</div>
<div class="listingblock">
<div class="title">Example6_15</div>
<div class="content">
<pre class="pygments highlight"><code data-lang="scala"><span></span><span class="tok-k">class</span> <span class="tok-nc">ThirtySecondsWindows</span>
    <span class="tok-k">extends</span> <span class="tok-nc">WindowAssigner</span><span class="tok-o">[</span><span class="tok-kt">Object</span>, <span class="tok-kt">TimeWindow</span><span class="tok-o">]</span> <span class="tok-o">{</span>

  <span class="tok-k">val</span> <span class="tok-n">windowSize</span><span class="tok-k">:</span> <span class="tok-kt">Long</span> <span class="tok-o">=</span> <span class="tok-mi">30</span> <span class="tok-o">*</span> <span class="tok-mi">1000L</span>

  <span class="tok-k">override</span> <span class="tok-k">def</span> <span class="tok-n">assignWindows</span><span class="tok-o">(</span>
    <span class="tok-n">o</span><span class="tok-k">:</span> <span class="tok-kt">Object</span><span class="tok-o">,</span>
    <span class="tok-n">ts</span><span class="tok-k">:</span> <span class="tok-kt">Long</span><span class="tok-o">,</span>
    <span class="tok-n">ctx</span><span class="tok-k">:</span> <span class="tok-kt">WindowAssigner.WindowAssignerContext</span><span class="tok-o">)</span><span class="tok-k">:</span> <span class="tok-kt">java.util.List</span><span class="tok-o">[</span><span class="tok-kt">TimeWindow</span><span class="tok-o">]</span> <span class="tok-k">=</span> <span class="tok-o">{</span>

    <span class="tok-k">val</span> <span class="tok-n">startTime</span> <span class="tok-k">=</span> <span class="tok-n">ts</span> <span class="tok-o">-</span> <span class="tok-o">(</span><span class="tok-n">ts</span> <span class="tok-o">%</span> <span class="tok-n">windowSize</span><span class="tok-o">)</span>
    <span class="tok-k">val</span> <span class="tok-n">endTime</span> <span class="tok-k">=</span> <span class="tok-n">startTime</span> <span class="tok-o">+</span> <span class="tok-n">windowSize</span>
    <span class="tok-nc">Collections</span><span class="tok-o">.</span><span class="tok-n">singletonList</span><span class="tok-o">(</span><span class="tok-k">new</span> <span class="tok-nc">TimeWindow</span><span class="tok-o">(</span><span class="tok-n">startTime</span><span class="tok-o">,</span> <span class="tok-n">endTime</span><span class="tok-o">))</span>
  <span class="tok-o">}</span>

  <span class="tok-k">override</span> <span class="tok-k">def</span> <span class="tok-n">getDefaultTrigger</span><span class="tok-o">(</span>
    <span class="tok-n">env</span><span class="tok-k">:</span> <span class="tok-kt">environment.StreamExecutionEnvironment</span><span class="tok-o">)</span><span class="tok-k">:</span> <span class="tok-kt">Trigger</span><span class="tok-o">[</span><span class="tok-kt">Object</span>, <span class="tok-kt">TimeWindow</span><span class="tok-o">]</span> <span class="tok-k">=</span> <span class="tok-o">{</span>
      <span class="tok-nc">EventTimeTrigger</span><span class="tok-o">.</span><span class="tok-n">create</span><span class="tok-o">()</span>
  <span class="tok-o">}</span>

  <span class="tok-k">override</span> <span class="tok-k">def</span> <span class="tok-n">getWindowSerializer</span><span class="tok-o">(</span>
    <span class="tok-n">executionConfig</span><span class="tok-k">:</span> <span class="tok-kt">ExecutionConfig</span><span class="tok-o">)</span><span class="tok-k">:</span> <span class="tok-kt">TypeSerializer</span><span class="tok-o">[</span><span class="tok-kt">TimeWindow</span><span class="tok-o">]</span> <span class="tok-k">=</span> <span class="tok-o">{</span>
    <span class="tok-k">new</span> <span class="tok-nc">TimeWindow</span><span class="tok-o">.</span><span class="tok-nc">Serializer</span>
  <span class="tok-o">}</span>

  <span class="tok-k">override</span> <span class="tok-k">def</span> <span class="tok-n">isEventTime</span> <span class="tok-k">=</span> <span class="tok-kc">true</span>
<span class="tok-o">}</span></code></pre>
</div>
</div>
<div class="paragraph">
<p>增量聚合示意图</p>
</div>
<div class="imageblock">
<div class="content">
<img src="images/spaf_0604.png" alt="spaf 0604">
</div>
</div>
<div class="paragraph">
<p>全窗口聚合示意图</p>
</div>
<div class="imageblock">
<div class="content">
<img src="images/spaf_0605.png" alt="spaf 0605">
</div>
</div>
<div class="paragraph">
<p>增量聚合和全窗口聚合结合使用的示意图</p>
</div>
<div class="imageblock">
<div class="content">
<img src="images/spaf_0606.png" alt="spaf 0606">
</div>
</div>
<div class="paragraph">
<p><strong>触发器(Triggers)</strong></p>
</div>
<div class="paragraph">
<p>触发器定义了window何时会被求值以及何时发送求值结果。触发器可以到了特定的时间触发也可以碰到特定的事件触发。例如：观察到事件数量符合一定条件或者观察到了特定的事件。</p>
</div>
<div class="paragraph">
<p>默认的触发器将会在两种情况下触发</p>
</div>
<div class="ulist">
<ul>
<li>
<p>处理时间：机器时间到达处理时间</p>
</li>
<li>
<p>事件时间：水位线超过了窗口的结束时间</p>
</li>
</ul>
</div>
<div class="paragraph">
<p>触发器可以访问流的时间属性以及定时器，还可以对state状态编程。所以触发器和process function一样强大。例如我们可以实现一个触发逻辑：当窗口接收到一定数量的元素时，触发器触发。再比如当窗口接收到一个特定元素时，触发器触发。还有就是当窗口接收到的元素里面包含特定模式(5秒钟内接收到了两个同样类型的事件)，触发器也可以触发。在一个事件时间的窗口中，一个自定义的触发器可以提前(在水位线没过窗口结束时间之前)计算和发射计算结果。这是一个常见的低延迟计算策略，尽管计算不完全，但不像默认的那样需要等待水位线没过窗口结束时间。</p>
</div>
<div class="paragraph">
<p>每次调用触发器都会产生一个TriggerResult来决定窗口接下来发生什么。TriggerResult可以取以下结果：</p>
</div>
<div class="ulist">
<ul>
<li>
<p>CONTINUE：什么都不做</p>
</li>
<li>
<p>FIRE：如果window operator有ProcessWindowFunction这个参数，将会调用这个ProcessWindowFunction。如果窗口仅有增量聚合函数(ReduceFunction或者AggregateFunction)作为参数，那么当前的聚合结果将会被发送。窗口的state不变。</p>
</li>
<li>
<p>PURGE：窗口所有内容包括窗口的元数据都将被丢弃。</p>
</li>
<li>
<p>FIRE_AND_PURGE：先对窗口进行求值，再将窗口中的内容丢弃。</p>
</li>
</ul>
</div>
<div class="paragraph">
<p>TriggerResult可能的取值使得我们可以实现很复杂的窗口逻辑。一个自定义触发器可以触发多次，可以计算或者更新结果，可以在发送结果之前清空窗口。</p>
</div>
<div class="paragraph">
<p>接下来我们看一下Trigger API：</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="pygments highlight"><code data-lang="java"><span></span><span class="tok-kd">public</span> <span class="tok-kd">abstract</span> <span class="tok-kd">class</span> <span class="tok-nc">Trigger</span><span class="tok-o">&lt;</span><span class="tok-n">T</span><span class="tok-o">,</span> <span class="tok-n">W</span> <span class="tok-kd">extends</span> <span class="tok-n">Window</span><span class="tok-o">&gt;</span>
    <span class="tok-kd">implements</span> <span class="tok-n">Serializable</span> <span class="tok-o">{</span>

  <span class="tok-n">TriggerResult</span> <span class="tok-nf">onElement</span><span class="tok-o">(</span>
    <span class="tok-kt">long</span> <span class="tok-n">timestamp</span><span class="tok-o">,</span>
    <span class="tok-n">W</span> <span class="tok-n">window</span><span class="tok-o">,</span>
    <span class="tok-n">TriggerContext</span> <span class="tok-n">ctx</span><span class="tok-o">);</span>

  <span class="tok-kd">public</span> <span class="tok-kd">abstract</span> <span class="tok-n">TriggerResult</span> <span class="tok-nf">onProcessingTime</span><span class="tok-o">(</span>
    <span class="tok-kt">long</span> <span class="tok-n">timestamp</span><span class="tok-o">,</span>
    <span class="tok-n">W</span> <span class="tok-n">window</span><span class="tok-o">,</span>
    <span class="tok-n">TriggerContext</span> <span class="tok-n">ctx</span><span class="tok-o">);</span>

  <span class="tok-kd">public</span> <span class="tok-kd">abstract</span> <span class="tok-n">TriggerResult</span> <span class="tok-nf">onEventTime</span><span class="tok-o">(</span>
    <span class="tok-kt">long</span> <span class="tok-n">timestamp</span><span class="tok-o">,</span>
    <span class="tok-n">W</span> <span class="tok-n">window</span><span class="tok-o">,</span>
    <span class="tok-n">TriggerContext</span> <span class="tok-n">ctx</span><span class="tok-o">);</span>

  <span class="tok-kd">public</span> <span class="tok-kt">boolean</span> <span class="tok-nf">canMerge</span><span class="tok-o">();</span>

  <span class="tok-kd">public</span> <span class="tok-kt">void</span> <span class="tok-nf">onMerge</span><span class="tok-o">(</span><span class="tok-n">W</span> <span class="tok-n">window</span><span class="tok-o">,</span> <span class="tok-n">OnMergeContext</span> <span class="tok-n">ctx</span><span class="tok-o">);</span>

  <span class="tok-kd">public</span> <span class="tok-kd">abstract</span> <span class="tok-kt">void</span> <span class="tok-nf">clear</span><span class="tok-o">(</span><span class="tok-n">W</span> <span class="tok-n">window</span><span class="tok-o">,</span> <span class="tok-n">TriggerContext</span> <span class="tok-n">ctx</span><span class="tok-o">);</span>
<span class="tok-o">}</span>

<span class="tok-kd">public</span> <span class="tok-kd">interface</span> <span class="tok-nc">TriggerContext</span> <span class="tok-o">{</span>

  <span class="tok-kt">long</span> <span class="tok-nf">getCurrentProcessingTime</span><span class="tok-o">();</span>

  <span class="tok-kt">long</span> <span class="tok-nf">getCurrentWatermark</span><span class="tok-o">();</span>

  <span class="tok-kt">void</span> <span class="tok-nf">registerProcessingTimeTimer</span><span class="tok-o">(</span><span class="tok-kt">long</span> <span class="tok-n">time</span><span class="tok-o">);</span>

  <span class="tok-kt">void</span> <span class="tok-nf">registerEventTimeTimer</span><span class="tok-o">(</span><span class="tok-kt">long</span> <span class="tok-n">time</span><span class="tok-o">);</span>

  <span class="tok-kt">void</span> <span class="tok-nf">registerEventTimeTimer</span><span class="tok-o">(</span><span class="tok-kt">long</span> <span class="tok-n">time</span><span class="tok-o">);</span>

  <span class="tok-kt">void</span> <span class="tok-nf">deleteProcessingTimeTimer</span><span class="tok-o">(</span><span class="tok-kt">long</span> <span class="tok-n">time</span><span class="tok-o">);</span>

  <span class="tok-kt">void</span> <span class="tok-nf">deleteEventTimeTimer</span><span class="tok-o">(</span><span class="tok-kt">long</span> <span class="tok-n">time</span><span class="tok-o">);</span>

  <span class="tok-o">&lt;</span><span class="tok-n">S</span> <span class="tok-kd">extends</span> <span class="tok-n">State</span><span class="tok-o">&gt;</span> <span class="tok-n">S</span> <span class="tok-nf">getPartitionedState</span><span class="tok-o">(</span>
    <span class="tok-n">StateDescriptor</span><span class="tok-o">&lt;</span><span class="tok-n">S</span><span class="tok-o">,</span> <span class="tok-o">?&gt;</span> <span class="tok-n">stateDescriptor</span><span class="tok-o">);</span>
<span class="tok-o">}</span>

<span class="tok-kd">public</span> <span class="tok-kd">interface</span> <span class="tok-nc">OnMergeContext</span> <span class="tok-kd">extends</span> <span class="tok-n">TriggerContext</span> <span class="tok-o">{</span>

  <span class="tok-kt">void</span> <span class="tok-nf">mergePartitionedState</span><span class="tok-o">(</span>
    <span class="tok-n">StateDescriptor</span><span class="tok-o">&lt;</span><span class="tok-n">S</span><span class="tok-o">,</span> <span class="tok-o">?&gt;</span> <span class="tok-n">stateDescriptor</span>
  <span class="tok-o">);</span>
<span class="tok-o">}</span></code></pre>
</div>
</div>
<div class="paragraph">
<p>这里要注意两个地方：清空state和merging合并触发器。</p>
</div>
<div class="paragraph">
<p>当在触发器中使用per-window state时，这里我们需要保证当窗口被删除时state也要被删除，否则随着时间的推移，window operator将会积累越来越多的数据，最终可能使应用崩溃。</p>
</div>
<div class="paragraph">
<p>当窗口被删除时，为了清空所有状态，触发器的clear()方法需要需要删掉所有的自定义per-window state，以及使用TriggerContext对象将处理时间和事件时间的定时器都删除。</p>
</div>
<div class="paragraph">
<p>下面的例子展示了一个触发器在窗口结束时间之前触发。当第一个事件被分配到窗口时，这个触发器注册了一个定时器，定时时间为水位线之前一秒钟。当定时事件执行，将会注册一个新的定时事件，这样，这个触发器每秒钟最多触发一次。</p>
</div>
<div class="listingblock">
<div class="title">Example6_16</div>
<div class="content">
<pre class="pygments highlight"><code data-lang="scala"><span></span><span class="tok-k">class</span> <span class="tok-nc">OneSecondIntervalTrigger</span>
    <span class="tok-k">extends</span> <span class="tok-nc">Trigger</span><span class="tok-o">[</span><span class="tok-kt">SensorReading</span>, <span class="tok-kt">TimeWindow</span><span class="tok-o">]</span> <span class="tok-o">{</span>

  <span class="tok-k">override</span> <span class="tok-k">def</span> <span class="tok-n">onElement</span><span class="tok-o">(</span>
    <span class="tok-n">r</span><span class="tok-k">:</span> <span class="tok-kt">SensorReading</span><span class="tok-o">,</span>
    <span class="tok-n">timestamp</span><span class="tok-k">:</span> <span class="tok-kt">Long</span><span class="tok-o">,</span>
    <span class="tok-n">window</span><span class="tok-k">:</span> <span class="tok-kt">TimeWindow</span><span class="tok-o">,</span>
    <span class="tok-n">ctx</span><span class="tok-k">:</span> <span class="tok-kt">Trigger.TriggerContext</span>
  <span class="tok-o">)</span><span class="tok-k">:</span> <span class="tok-kt">TriggerResult</span> <span class="tok-o">=</span> <span class="tok-o">{</span>
    <span class="tok-k">val</span> <span class="tok-n">firstSeen</span><span class="tok-k">:</span> <span class="tok-kt">ValueState</span><span class="tok-o">[</span><span class="tok-kt">Boolean</span><span class="tok-o">]</span> <span class="tok-k">=</span> <span class="tok-n">ctx</span>
      <span class="tok-o">.</span><span class="tok-n">getPartitionedState</span><span class="tok-o">(</span>
        <span class="tok-k">new</span> <span class="tok-nc">ValueStateDescriptor</span><span class="tok-o">[</span><span class="tok-kt">Boolean</span><span class="tok-o">](</span>
          <span class="tok-s">&quot;firstSeen&quot;</span><span class="tok-o">,</span> <span class="tok-n">classOf</span><span class="tok-o">[</span><span class="tok-kt">Boolean</span><span class="tok-o">]</span>
        <span class="tok-o">)</span>
      <span class="tok-o">)</span>

    <span class="tok-k">if</span> <span class="tok-o">(!</span><span class="tok-n">firstSeen</span><span class="tok-o">.</span><span class="tok-n">value</span><span class="tok-o">())</span> <span class="tok-o">{</span>
      <span class="tok-k">val</span> <span class="tok-n">t</span> <span class="tok-k">=</span> <span class="tok-n">ctx</span><span class="tok-o">.</span><span class="tok-n">getCurrentWatermark</span> <span class="tok-o">+</span> <span class="tok-o">(</span><span class="tok-mi">1000</span> <span class="tok-o">-</span> <span class="tok-o">(</span><span class="tok-n">ctx</span><span class="tok-o">.</span><span class="tok-n">getCurrentWatermark</span> <span class="tok-o">%</span> <span class="tok-mi">1000</span><span class="tok-o">))</span>
      <span class="tok-n">ctx</span><span class="tok-o">.</span><span class="tok-n">registerEventTimeTimer</span><span class="tok-o">(</span><span class="tok-n">t</span><span class="tok-o">)</span>
      <span class="tok-n">ctx</span><span class="tok-o">.</span><span class="tok-n">registerEventTimeTimer</span><span class="tok-o">(</span><span class="tok-n">window</span><span class="tok-o">.</span><span class="tok-n">getEnd</span><span class="tok-o">)</span>
      <span class="tok-n">firstSeen</span><span class="tok-o">.</span><span class="tok-n">update</span><span class="tok-o">(</span><span class="tok-kc">true</span><span class="tok-o">)</span>
    <span class="tok-o">}</span>

    <span class="tok-nc">TriggerResult</span><span class="tok-o">.</span><span class="tok-nc">CONTINUE</span>
  <span class="tok-o">}</span>

  <span class="tok-k">override</span> <span class="tok-k">def</span> <span class="tok-n">onEventTime</span><span class="tok-o">(</span>
    <span class="tok-n">timestamp</span><span class="tok-k">:</span> <span class="tok-kt">Long</span><span class="tok-o">,</span>
    <span class="tok-n">window</span><span class="tok-k">:</span> <span class="tok-kt">TimeWindow</span><span class="tok-o">,</span>
    <span class="tok-n">ctx</span><span class="tok-k">:</span> <span class="tok-kt">Trigger.TriggerContext</span>
  <span class="tok-o">)</span><span class="tok-k">:</span> <span class="tok-kt">TriggerResult</span> <span class="tok-o">=</span> <span class="tok-o">{</span>
    <span class="tok-k">if</span> <span class="tok-o">(</span><span class="tok-n">timestamp</span> <span class="tok-o">==</span> <span class="tok-n">window</span><span class="tok-o">.</span><span class="tok-n">getEnd</span><span class="tok-o">)</span> <span class="tok-o">{</span>
      <span class="tok-nc">TriggerResult</span><span class="tok-o">.</span><span class="tok-nc">FIRE_AND_PURGE</span>
    <span class="tok-o">}</span> <span class="tok-k">else</span> <span class="tok-o">{</span>
      <span class="tok-k">val</span> <span class="tok-n">t</span> <span class="tok-k">=</span> <span class="tok-n">ctx</span><span class="tok-o">.</span><span class="tok-n">getCurrentWatermark</span> <span class="tok-o">+</span> <span class="tok-o">(</span><span class="tok-mi">1000</span> <span class="tok-o">-</span> <span class="tok-o">(</span><span class="tok-n">ctx</span><span class="tok-o">.</span><span class="tok-n">getCurrentWatermark</span> <span class="tok-o">%</span> <span class="tok-mi">1000</span><span class="tok-o">))</span>
      <span class="tok-k">if</span> <span class="tok-o">(</span><span class="tok-n">t</span> <span class="tok-o">&lt;</span> <span class="tok-n">window</span><span class="tok-o">.</span><span class="tok-n">getEnd</span><span class="tok-o">)</span> <span class="tok-o">{</span>
        <span class="tok-n">ctx</span><span class="tok-o">.</span><span class="tok-n">registerEventTimeTimer</span><span class="tok-o">(</span><span class="tok-n">t</span><span class="tok-o">)</span>
      <span class="tok-o">}</span>
      <span class="tok-nc">TriggerResult</span><span class="tok-o">.</span><span class="tok-nc">FIRE</span>
    <span class="tok-o">}</span>
  <span class="tok-o">}</span>

  <span class="tok-k">override</span> <span class="tok-k">def</span> <span class="tok-n">onProcessingTime</span><span class="tok-o">(</span>
    <span class="tok-n">timestamp</span><span class="tok-k">:</span> <span class="tok-kt">Long</span><span class="tok-o">,</span>
    <span class="tok-n">window</span><span class="tok-k">:</span> <span class="tok-kt">TimeWindow</span><span class="tok-o">,</span>
    <span class="tok-n">ctx</span><span class="tok-k">:</span> <span class="tok-kt">Trigger.TriggerContext</span>
  <span class="tok-o">)</span><span class="tok-k">:</span> <span class="tok-kt">TriggerResult</span> <span class="tok-o">=</span> <span class="tok-o">{</span>
    <span class="tok-nc">TriggerResult</span><span class="tok-o">.</span><span class="tok-nc">CONTINUE</span>
  <span class="tok-o">}</span>

  <span class="tok-k">override</span> <span class="tok-k">def</span> <span class="tok-n">clear</span><span class="tok-o">(</span>
    <span class="tok-n">window</span><span class="tok-k">:</span> <span class="tok-kt">TimeWindow</span><span class="tok-o">,</span>
    <span class="tok-n">ctx</span><span class="tok-k">:</span> <span class="tok-kt">Trigger.TriggerContext</span>
  <span class="tok-o">)</span><span class="tok-k">:</span> <span class="tok-kt">Unit</span> <span class="tok-o">=</span> <span class="tok-o">{</span>
    <span class="tok-k">val</span> <span class="tok-n">firstSeen</span><span class="tok-k">:</span> <span class="tok-kt">ValueState</span><span class="tok-o">[</span><span class="tok-kt">Boolean</span><span class="tok-o">]</span> <span class="tok-k">=</span> <span class="tok-n">ctx</span>
      <span class="tok-o">.</span><span class="tok-n">getPartitionedState</span><span class="tok-o">(</span>
        <span class="tok-k">new</span> <span class="tok-nc">ValueStateDescriptor</span><span class="tok-o">[</span><span class="tok-kt">Boolean</span><span class="tok-o">](</span>
          <span class="tok-s">&quot;firstSeen&quot;</span><span class="tok-o">,</span> <span class="tok-n">classOf</span><span class="tok-o">[</span><span class="tok-kt">Boolean</span><span class="tok-o">]</span>
        <span class="tok-o">)</span>
      <span class="tok-o">)</span>
    <span class="tok-n">firstSeen</span><span class="tok-o">.</span><span class="tok-n">clear</span><span class="tok-o">()</span>
  <span class="tok-o">}</span>
<span class="tok-o">}</span></code></pre>
</div>
</div>
<div class="paragraph">
<p><strong>清理器(EVICTORS)</strong></p>
</div>
<div class="paragraph">
<p>evictor可以在window function求值之前或者之后移除窗口中的元素。</p>
</div>
<div class="paragraph">
<p>我们看一下Evictor的接口定义：</p>
</div>
<div class="listingblock">
<div class="title">Example6_17</div>
<div class="content">
<pre class="pygments highlight"><code data-lang="java"><span></span><span class="tok-kd">public</span> <span class="tok-kd">interface</span> <span class="tok-nc">Evictor</span><span class="tok-o">&lt;</span><span class="tok-n">T</span><span class="tok-o">,</span> <span class="tok-n">W</span> <span class="tok-kd">extends</span> <span class="tok-n">Window</span><span class="tok-o">&gt;</span>
    <span class="tok-kd">extends</span> <span class="tok-n">Serializable</span> <span class="tok-o">{</span>
  <span class="tok-kt">void</span> <span class="tok-nf">evictBefore</span><span class="tok-o">(</span>
    <span class="tok-n">Iterable</span><span class="tok-o">&lt;</span><span class="tok-n">TimestampedValue</span><span class="tok-o">&lt;</span><span class="tok-n">T</span><span class="tok-o">&gt;&gt;</span> <span class="tok-n">elements</span><span class="tok-o">,</span>
    <span class="tok-kt">int</span> <span class="tok-n">size</span><span class="tok-o">,</span>
    <span class="tok-n">W</span> <span class="tok-n">window</span><span class="tok-o">,</span>
    <span class="tok-n">EvictorContext</span> <span class="tok-n">evictorContext</span><span class="tok-o">);</span>

  <span class="tok-kt">void</span> <span class="tok-nf">evictAfter</span><span class="tok-o">(</span>
    <span class="tok-n">Iterable</span><span class="tok-o">&lt;</span><span class="tok-n">TimestampedValue</span><span class="tok-o">&lt;</span><span class="tok-n">T</span><span class="tok-o">&gt;&gt;</span> <span class="tok-n">elements</span><span class="tok-o">,</span>
    <span class="tok-kt">int</span> <span class="tok-n">size</span><span class="tok-o">,</span>
    <span class="tok-n">W</span> <span class="tok-n">window</span><span class="tok-o">,</span>
    <span class="tok-n">EvictorContext</span> <span class="tok-n">evictorContext</span><span class="tok-o">);</span>

  <span class="tok-kd">interface</span> <span class="tok-nc">EvictorContext</span> <span class="tok-o">{</span>

    <span class="tok-kt">long</span> <span class="tok-nf">getCurrentProcessingTime</span><span class="tok-o">();</span>

    <span class="tok-kt">long</span> <span class="tok-nf">getCurrentWatermark</span><span class="tok-o">();</span>
  <span class="tok-o">}</span>
<span class="tok-o">}</span></code></pre>
</div>
</div>
<div class="paragraph">
<p>evictBefore()和evictAfter()分别在window function计算之前或者之后调用。Iterable迭代器包含了窗口所有的元素，size为窗口中元素的数量，window object和EvictorContext可以访问当前处理时间和水位线。可以对Iterator调用remove()方法来移除窗口中的元素。</p>
</div>
<div class="paragraph">
<p>evictor也经常被用在GlobalWindow上，用来清楚部分元素，而不是将窗口中的元素全部清空。</p>
</div>
</div>
</div>
<div class="sect2">
<h3 id="_处理迟到的元素handling_late_data">6.4. 处理迟到的元素(Handling Late Data)</h3>
<div class="paragraph">
<p>水位线可以用来平衡计算的完整性和延迟两方面。除非我们选择一种非常保守的水位线策略(最大延时设置的非常大，以至于包含了所有的元素，但结果是非常大的延迟)，否则我们总需要处理迟到的元素。</p>
</div>
<div class="paragraph">
<p>迟到的元素是指当这个元素来到时，这个元素所对应的窗口已经计算完毕了(也就是说水位线已经没过窗口结束时间了)。这说明迟到这个特性只针对事件时间。</p>
</div>
<div class="paragraph">
<p>DataStream API提供了三种策略来处理迟到元素</p>
</div>
<div class="ulist">
<ul>
<li>
<p>直接抛弃迟到的元素</p>
</li>
<li>
<p>将迟到的元素发送到另一条流中去</p>
</li>
<li>
<p>可以更新窗口已经计算完的结果，并发出计算结果。</p>
</li>
</ul>
</div>
<div class="sect3">
<h4 id="_抛弃迟到元素">6.4.1. 抛弃迟到元素</h4>
<div class="paragraph">
<p>抛弃迟到的元素是event time window operator的默认行为。也就是说一个迟到的元素不会创建一个新的窗口。</p>
</div>
<div class="paragraph">
<p>process function可以通过比较迟到元素的时间戳和当前水位线的大小来很轻易的过滤掉迟到元素。</p>
</div>
</div>
<div class="sect3">
<h4 id="_重定向迟到元素">6.4.2. 重定向迟到元素</h4>
<div class="paragraph">
<p>迟到的元素也可以使用侧输出(side output)特性被重定向到另外的一条流中去。迟到元素所组成的侧输出流可以继续处理或者sink到持久化设施中去。</p>
</div>
<div class="paragraph">
<p>例子</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="pygments highlight"><code data-lang="scala"><span></span><span class="tok-k">val</span> <span class="tok-n">readings</span><span class="tok-k">:</span> <span class="tok-kt">DataStream</span><span class="tok-o">[</span><span class="tok-kt">SensorReading</span><span class="tok-o">]</span> <span class="tok-k">=</span> <span class="tok-o">???</span>

<span class="tok-k">val</span> <span class="tok-n">countPer10Secs</span><span class="tok-k">:</span> <span class="tok-kt">DataStream</span><span class="tok-o">[(</span><span class="tok-kt">String</span>, <span class="tok-kt">Long</span>, <span class="tok-kt">Int</span><span class="tok-o">)]</span> <span class="tok-k">=</span> <span class="tok-n">readings</span>
  <span class="tok-o">.</span><span class="tok-n">keyBy</span><span class="tok-o">(</span><span class="tok-k">_</span><span class="tok-o">.</span><span class="tok-n">id</span><span class="tok-o">)</span>
  <span class="tok-o">.</span><span class="tok-n">timeWindow</span><span class="tok-o">(</span><span class="tok-nc">Time</span><span class="tok-o">.</span><span class="tok-n">seconds</span><span class="tok-o">(</span><span class="tok-mi">10</span><span class="tok-o">))</span>
  <span class="tok-o">.</span><span class="tok-n">sideOutputLateData</span><span class="tok-o">(</span><span class="tok-k">new</span> <span class="tok-nc">OutputTag</span><span class="tok-o">[</span><span class="tok-kt">SensorReading</span><span class="tok-o">](</span><span class="tok-s">&quot;late-readings&quot;</span><span class="tok-o">))</span>
  <span class="tok-o">.</span><span class="tok-n">process</span><span class="tok-o">(</span><span class="tok-k">new</span> <span class="tok-nc">CountFunction</span><span class="tok-o">())</span>

<span class="tok-k">val</span> <span class="tok-n">lateStream</span><span class="tok-k">:</span> <span class="tok-kt">DataStream</span><span class="tok-o">[</span><span class="tok-kt">SensorReading</span><span class="tok-o">]</span> <span class="tok-k">=</span> <span class="tok-n">countPer10Secs</span>
  <span class="tok-o">.</span><span class="tok-n">getSideOutput</span><span class="tok-o">(</span><span class="tok-k">new</span> <span class="tok-nc">OutputTag</span><span class="tok-o">[</span><span class="tok-kt">SensorReading</span><span class="tok-o">](</span><span class="tok-s">&quot;late-readings&quot;</span><span class="tok-o">))</span></code></pre>
</div>
</div>
<div class="paragraph">
<p>下面这个例子展示了ProcessFunction如何过滤掉迟到的元素然后将迟到的元素发送到侧输出流中去。</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="pygments highlight"><code data-lang="scala"><span></span><span class="tok-k">val</span> <span class="tok-n">readings</span><span class="tok-k">:</span> <span class="tok-kt">DataStream</span><span class="tok-o">[</span><span class="tok-kt">SensorReading</span><span class="tok-o">]</span> <span class="tok-k">=</span> <span class="tok-o">???</span>
<span class="tok-k">val</span> <span class="tok-n">filteredReadings</span><span class="tok-k">:</span> <span class="tok-kt">DataStream</span><span class="tok-o">[</span><span class="tok-kt">SensorReading</span><span class="tok-o">]</span> <span class="tok-k">=</span> <span class="tok-n">readings</span>
  <span class="tok-o">.</span><span class="tok-n">process</span><span class="tok-o">(</span><span class="tok-k">new</span> <span class="tok-nc">LateReadingsFilter</span><span class="tok-o">)</span>

<span class="tok-c1">// retrieve late readings</span>
<span class="tok-k">val</span> <span class="tok-n">lateReadings</span><span class="tok-k">:</span> <span class="tok-kt">DataStream</span><span class="tok-o">[</span><span class="tok-kt">SensorReading</span><span class="tok-o">]</span> <span class="tok-k">=</span> <span class="tok-n">filteredReadings</span>
  <span class="tok-o">.</span><span class="tok-n">getSideOutput</span><span class="tok-o">(</span><span class="tok-k">new</span> <span class="tok-nc">OutputTag</span><span class="tok-o">[</span><span class="tok-kt">SensorReading</span><span class="tok-o">](</span><span class="tok-s">&quot;late-readings&quot;</span><span class="tok-o">))</span>


<span class="tok-cm">/** A ProcessFunction that filters out late sensor readings and</span>
<span class="tok-cm">  * re-directs them to a side output */</span>
<span class="tok-k">class</span> <span class="tok-nc">LateReadingsFilter</span>
    <span class="tok-k">extends</span> <span class="tok-nc">ProcessFunction</span><span class="tok-o">[</span><span class="tok-kt">SensorReading</span>, <span class="tok-kt">SensorReading</span><span class="tok-o">]</span> <span class="tok-o">{</span>

  <span class="tok-k">val</span> <span class="tok-n">lateReadingsOut</span> <span class="tok-k">=</span> <span class="tok-k">new</span> <span class="tok-nc">OutputTag</span><span class="tok-o">[</span><span class="tok-kt">SensorReading</span><span class="tok-o">](</span><span class="tok-s">&quot;late-readings&quot;</span><span class="tok-o">)</span>

  <span class="tok-k">override</span> <span class="tok-k">def</span> <span class="tok-n">processElement</span><span class="tok-o">(</span>
      <span class="tok-n">r</span><span class="tok-k">:</span> <span class="tok-kt">SensorReading</span><span class="tok-o">,</span>
      <span class="tok-n">ctx</span><span class="tok-k">:</span> <span class="tok-kt">ProcessFunction</span><span class="tok-o">[</span><span class="tok-kt">SensorReading</span>, <span class="tok-kt">SensorReading</span><span class="tok-o">]</span><span class="tok-k">#</span><span class="tok-nc">Context</span><span class="tok-o">,</span>
      <span class="tok-n">out</span><span class="tok-k">:</span> <span class="tok-kt">Collector</span><span class="tok-o">[</span><span class="tok-kt">SensorReading</span><span class="tok-o">])</span><span class="tok-k">:</span> <span class="tok-kt">Unit</span> <span class="tok-o">=</span> <span class="tok-o">{</span>

    <span class="tok-c1">// compare record timestamp with current watermark</span>
    <span class="tok-k">if</span> <span class="tok-o">(</span><span class="tok-n">r</span><span class="tok-o">.</span><span class="tok-n">timestamp</span> <span class="tok-o">&lt;</span> <span class="tok-n">ctx</span><span class="tok-o">.</span><span class="tok-n">timerService</span><span class="tok-o">().</span><span class="tok-n">currentWatermark</span><span class="tok-o">())</span> <span class="tok-o">{</span>
      <span class="tok-c1">// this is a late reading =&gt; redirect it to the side output</span>
      <span class="tok-n">ctx</span><span class="tok-o">.</span><span class="tok-n">output</span><span class="tok-o">(</span><span class="tok-n">lateReadingsOut</span><span class="tok-o">,</span> <span class="tok-n">r</span><span class="tok-o">)</span>
    <span class="tok-o">}</span> <span class="tok-k">else</span> <span class="tok-o">{</span>
      <span class="tok-n">out</span><span class="tok-o">.</span><span class="tok-n">collect</span><span class="tok-o">(</span><span class="tok-n">r</span><span class="tok-o">)</span>
    <span class="tok-o">}</span>
  <span class="tok-o">}</span>
<span class="tok-o">}</span></code></pre>
</div>
</div>
</div>
<div class="sect3">
<h4 id="_使用迟到元素更新窗口计算结果updating_results_by_including_late_events">6.4.3. 使用迟到元素更新窗口计算结果(Updating Results by Including Late Events)</h4>
<div class="paragraph">
<p>由于存在迟到的元素，所以已经计算出的窗口结果是不准确和不完全的。我们可以使用迟到元素更新已经计算完的窗口结果。</p>
</div>
<div class="paragraph">
<p>如果我们要求一个operator支持重新计算和更新已经发出的结果，就需要在第一次发出结果以后也要保存之前所有的状态。但显然我们不能一直保存所有的状态，肯定会在某一个时间点将状态清空，而一旦状态被清空，结果就再也不能重新计算或者更新了。而迟到的元素只能被抛弃或者发送到侧输出流。</p>
</div>
<div class="paragraph">
<p>window operator API提供了方法来明确声明我们要等待迟到元素。当使用event-time window，我们可以指定一个时间段叫做allowed lateness。window operator如果设置了allowed lateness，这个window operator在水位线没过窗口结束时间时也将不会删除窗口和窗口中的状态。窗口会在一段时间内(allowed lateness设置的)保留所有的元素。</p>
</div>
<div class="paragraph">
<p>当迟到元素在allowed lateness时间内到达时，这个迟到元素会被实时处理并发送到触发器(trigger)。当水位线没过了窗口结束时间+allowed lateness时间时，窗口会被删除，并且所有后来的迟到的元素都会被丢弃。</p>
</div>
<div class="paragraph">
<p>Allowed lateness可以使用allowedLateness()方法来指定，如下所示：</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="pygments highlight"><code data-lang="scala"><span></span><span class="tok-k">val</span> <span class="tok-n">readings</span><span class="tok-k">:</span> <span class="tok-kt">DataStream</span><span class="tok-o">[</span><span class="tok-kt">SensorReading</span><span class="tok-o">]</span> <span class="tok-k">=</span> <span class="tok-o">???</span>

<span class="tok-k">val</span> <span class="tok-n">countPer10Secs</span><span class="tok-k">:</span> <span class="tok-kt">DataStream</span><span class="tok-o">[(</span><span class="tok-kt">String</span>, <span class="tok-kt">Long</span>, <span class="tok-kt">Int</span>, <span class="tok-kt">String</span><span class="tok-o">)]</span> <span class="tok-k">=</span> <span class="tok-n">readings</span>
  <span class="tok-o">.</span><span class="tok-n">keyBy</span><span class="tok-o">(</span><span class="tok-k">_</span><span class="tok-o">.</span><span class="tok-n">id</span><span class="tok-o">)</span>
  <span class="tok-o">.</span><span class="tok-n">timeWindow</span><span class="tok-o">(</span><span class="tok-nc">Time</span><span class="tok-o">.</span><span class="tok-n">seconds</span><span class="tok-o">(</span><span class="tok-mi">10</span><span class="tok-o">))</span>
  <span class="tok-c1">// process late readings for 5 additional seconds</span>
  <span class="tok-o">.</span><span class="tok-n">allowedLateness</span><span class="tok-o">(</span><span class="tok-nc">Time</span><span class="tok-o">.</span><span class="tok-n">seconds</span><span class="tok-o">(</span><span class="tok-mi">5</span><span class="tok-o">))</span>
  <span class="tok-c1">// count readings and update results if late readings arrive</span>
  <span class="tok-o">.</span><span class="tok-n">process</span><span class="tok-o">(</span><span class="tok-k">new</span> <span class="tok-nc">UpdatingWindowCountFunction</span><span class="tok-o">)</span>

  <span class="tok-cm">/** A counting WindowProcessFunction that distinguishes between</span>
<span class="tok-cm">  * first results and updates. */</span>
<span class="tok-k">class</span> <span class="tok-nc">UpdatingWindowCountFunction</span>
    <span class="tok-k">extends</span> <span class="tok-nc">ProcessWindowFunction</span><span class="tok-o">[</span>
            <span class="tok-kt">SensorReading</span>, <span class="tok-o">(</span><span class="tok-kt">String</span>, <span class="tok-kt">Long</span>, <span class="tok-kt">Int</span>, <span class="tok-kt">String</span><span class="tok-o">)</span>, <span class="tok-kt">String</span>, <span class="tok-kt">TimeWindow</span><span class="tok-o">]</span> <span class="tok-o">{</span>

  <span class="tok-k">override</span> <span class="tok-k">def</span> <span class="tok-n">process</span><span class="tok-o">(</span>
      <span class="tok-n">id</span><span class="tok-k">:</span> <span class="tok-kt">String</span><span class="tok-o">,</span>
      <span class="tok-n">ctx</span><span class="tok-k">:</span> <span class="tok-kt">Context</span><span class="tok-o">,</span>
      <span class="tok-n">elements</span><span class="tok-k">:</span> <span class="tok-kt">Iterable</span><span class="tok-o">[</span><span class="tok-kt">SensorReading</span><span class="tok-o">],</span>
      <span class="tok-n">out</span><span class="tok-k">:</span> <span class="tok-kt">Collector</span><span class="tok-o">[(</span><span class="tok-kt">String</span>, <span class="tok-kt">Long</span>, <span class="tok-kt">Int</span>, <span class="tok-kt">String</span><span class="tok-o">)])</span><span class="tok-k">:</span> <span class="tok-kt">Unit</span> <span class="tok-o">=</span> <span class="tok-o">{</span>

    <span class="tok-c1">// count the number of readings</span>
    <span class="tok-k">val</span> <span class="tok-n">cnt</span> <span class="tok-k">=</span> <span class="tok-n">elements</span><span class="tok-o">.</span><span class="tok-n">count</span><span class="tok-o">(</span><span class="tok-k">_</span> <span class="tok-k">=&gt;</span> <span class="tok-kc">true</span><span class="tok-o">)</span>

    <span class="tok-c1">// state to check if this is the first evaluation of the window or not</span>
    <span class="tok-k">val</span> <span class="tok-n">isUpdate</span> <span class="tok-k">=</span> <span class="tok-n">ctx</span><span class="tok-o">.</span><span class="tok-n">windowState</span><span class="tok-o">.</span><span class="tok-n">getState</span><span class="tok-o">(</span>
      <span class="tok-k">new</span> <span class="tok-nc">ValueStateDescriptor</span><span class="tok-o">[</span><span class="tok-kt">Boolean</span><span class="tok-o">](</span><span class="tok-s">&quot;isUpdate&quot;</span><span class="tok-o">,</span> <span class="tok-nc">Types</span><span class="tok-o">.</span><span class="tok-n">of</span><span class="tok-o">[</span><span class="tok-kt">Boolean</span><span class="tok-o">]))</span>

    <span class="tok-k">if</span> <span class="tok-o">(!</span><span class="tok-n">isUpdate</span><span class="tok-o">.</span><span class="tok-n">value</span><span class="tok-o">())</span> <span class="tok-o">{</span>
      <span class="tok-c1">// first evaluation, emit first result</span>
      <span class="tok-n">out</span><span class="tok-o">.</span><span class="tok-n">collect</span><span class="tok-o">((</span><span class="tok-n">id</span><span class="tok-o">,</span> <span class="tok-n">ctx</span><span class="tok-o">.</span><span class="tok-n">window</span><span class="tok-o">.</span><span class="tok-n">getEnd</span><span class="tok-o">,</span> <span class="tok-n">cnt</span><span class="tok-o">,</span> <span class="tok-s">&quot;first&quot;</span><span class="tok-o">))</span>
      <span class="tok-n">isUpdate</span><span class="tok-o">.</span><span class="tok-n">update</span><span class="tok-o">(</span><span class="tok-kc">true</span><span class="tok-o">)</span>
    <span class="tok-o">}</span> <span class="tok-k">else</span> <span class="tok-o">{</span>
      <span class="tok-c1">// not the first evaluation, emit an update</span>
      <span class="tok-n">out</span><span class="tok-o">.</span><span class="tok-n">collect</span><span class="tok-o">((</span><span class="tok-n">id</span><span class="tok-o">,</span> <span class="tok-n">ctx</span><span class="tok-o">.</span><span class="tok-n">window</span><span class="tok-o">.</span><span class="tok-n">getEnd</span><span class="tok-o">,</span> <span class="tok-n">cnt</span><span class="tok-o">,</span> <span class="tok-s">&quot;update&quot;</span><span class="tok-o">))</span>
    <span class="tok-o">}</span>
  <span class="tok-o">}</span>
<span class="tok-o">}</span></code></pre>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="sect1">
<h2 id="_有状态的计算">7. 有状态的计算</h2>
<div class="sectionbody">
<div class="paragraph">
<p>状态操作符和用户自定义函数都是我们在写流处理程序时，常用的工具。事实上，大部分稍微复杂一点的逻辑都需要保存数据或者保存计算结果。很多Flink内置的操作符例如：source操作符，sink操作符等等都是有状态的，也就是说会缓存流数据或者计算结果。例如，窗口操作符将会为ProcessWindowFunction收集输入的数据，或者收集ReduceFunction计算的结果。而ProcessFunction也会保存定时器事件，一些sink方法为了做到exactly-once，会将事务保存下来。除了内置的操作符以及提供的source和sink操作符，Flink的DataStream API还在UDF函数中暴露了可以注册、保存和访问状态的接口。</p>
</div>
<div class="paragraph">
<p>本章重点讨论有状态的用户自定义函数的实现，以及讨论有状态应用的性能和健壮性。特别的，我们将解释在用户自定义函数中，如何定义不同类型的状态，以及如何与状态进行交互。我们还讨论了性能方面的问题以及如何控制状态大小的问题。</p>
</div>
<div class="sect2">
<h3 id="_实现有状态的用户自定义函数">7.1. 实现有状态的用户自定义函数</h3>
<div class="paragraph">
<p>我们知道函数有两种状态，键控状态(keyed state)和操作符状态(operator state)。</p>
</div>
<div class="sect3">
<h4 id="_在runtimecontext中定义键控状态keyed_state">7.1.1. 在RuntimeContext中定义键控状态(keyed state)</h4>
<div class="paragraph">
<p>用户自定义函数可以使用keyed state来存储和访问key对应的状态。对于每一个key，Flink将会维护一个状态实例。一个操作符的状态实例将会被分发到操作符的所有并行任务中去。这表明函数的每一个并行任务只为所有key的某一部分key保存key对应的状态实例。所以keyed state和分布式key-value map数据结构非常类似。</p>
</div>
<div class="paragraph">
<p>keyed state仅可用于KeyedStream。Flink支持以下数据类型的状态变量：</p>
</div>
<div class="ulist">
<ul>
<li>
<p>ValueState[T]保存单个的值，值的类型为T。</p>
<div class="ulist">
<ul>
<li>
<p>get操作: ValueState.value()</p>
</li>
<li>
<p>set操作: ValueState.update(value: T)</p>
</li>
</ul>
</div>
</li>
<li>
<p>ListState[T]保存一个列表，列表里的元素的数据类型为T。基本操作如下：</p>
<div class="ulist">
<ul>
<li>
<p>ListState.add(value: T)</p>
</li>
<li>
<p>ListState.addAll(values: java.util.List[T])</p>
</li>
<li>
<p>ListState.get()返回Iterable[T]</p>
</li>
<li>
<p>ListState.update(values: java.util.List[T])</p>
</li>
</ul>
</div>
</li>
<li>
<p>MapState[K, V]保存Key-Value对。</p>
<div class="ulist">
<ul>
<li>
<p>MapState.get(key: K)</p>
</li>
<li>
<p>MapState.put(key: K, value: V)</p>
</li>
<li>
<p>MapState.contains(key: K)</p>
</li>
<li>
<p>MapState.remove(key: K)</p>
</li>
</ul>
</div>
</li>
<li>
<p>ReducingState[T]</p>
</li>
<li>
<p>AggregatingState[I, O]</p>
</li>
</ul>
</div>
<div class="paragraph">
<p>State.clear()是清空操作。</p>
</div>
<div class="listingblock">
<div class="title">Example 7-1. 在FlatMapFunction中使用keyed ValueState</div>
<div class="content">
<pre class="pygments highlight"><code data-lang="scala"><span></span><span class="tok-k">val</span> <span class="tok-n">sensorData</span><span class="tok-k">:</span> <span class="tok-kt">DataStream</span><span class="tok-o">[</span><span class="tok-kt">SensorReading</span><span class="tok-o">]</span> <span class="tok-k">=</span> <span class="tok-o">...</span>
<span class="tok-k">val</span> <span class="tok-n">keyedData</span><span class="tok-k">:</span> <span class="tok-kt">KeyedStream</span><span class="tok-o">[</span><span class="tok-kt">SensorReading</span>, <span class="tok-kt">String</span><span class="tok-o">]</span> <span class="tok-k">=</span> <span class="tok-n">sensorData</span><span class="tok-o">.</span><span class="tok-n">keyBy</span><span class="tok-o">(</span><span class="tok-k">_</span><span class="tok-o">.</span><span class="tok-n">id</span><span class="tok-o">)</span>

<span class="tok-k">val</span> <span class="tok-n">alerts</span><span class="tok-k">:</span> <span class="tok-kt">DataStream</span><span class="tok-o">[(</span><span class="tok-kt">String</span>, <span class="tok-kt">Double</span>, <span class="tok-kt">Double</span><span class="tok-o">)]</span> <span class="tok-k">=</span> <span class="tok-n">keyedData</span>
  <span class="tok-o">.</span><span class="tok-n">flatMap</span><span class="tok-o">(</span><span class="tok-k">new</span> <span class="tok-nc">TemperatureAlertFunction</span><span class="tok-o">(</span><span class="tok-mf">1.7</span><span class="tok-o">))</span>

<span class="tok-k">class</span> <span class="tok-nc">TemperatureAlertFunction</span><span class="tok-o">(</span><span class="tok-k">val</span> <span class="tok-n">threshold</span><span class="tok-k">:</span> <span class="tok-kt">Double</span><span class="tok-o">)</span> <span class="tok-k">extends</span> <span class="tok-nc">RichFlatMapFunction</span><span class="tok-o">[</span><span class="tok-kt">SensorReading</span>, <span class="tok-o">(</span><span class="tok-kt">String</span>, <span class="tok-kt">Double</span>, <span class="tok-kt">Double</span><span class="tok-o">)]</span> <span class="tok-o">{</span>
  <span class="tok-k">private</span> <span class="tok-k">var</span> <span class="tok-n">lastTempState</span><span class="tok-k">:</span> <span class="tok-kt">ValueState</span><span class="tok-o">[</span><span class="tok-kt">Double</span><span class="tok-o">]</span> <span class="tok-k">=</span> <span class="tok-k">_</span>

  <span class="tok-k">override</span> <span class="tok-k">def</span> <span class="tok-n">open</span><span class="tok-o">(</span><span class="tok-n">parameters</span><span class="tok-k">:</span> <span class="tok-kt">Configuration</span><span class="tok-o">)</span><span class="tok-k">:</span> <span class="tok-kt">Unit</span> <span class="tok-o">=</span> <span class="tok-o">{</span>
    <span class="tok-k">val</span> <span class="tok-n">lastTempDescriptor</span> <span class="tok-k">=</span> <span class="tok-k">new</span> <span class="tok-nc">ValueStateDescriptor</span><span class="tok-o">[</span><span class="tok-kt">Double</span><span class="tok-o">](</span><span class="tok-s">&quot;lastTemp&quot;</span><span class="tok-o">,</span> <span class="tok-n">classOf</span><span class="tok-o">[</span><span class="tok-kt">Double</span><span class="tok-o">])</span>

    <span class="tok-n">lastTempState</span> <span class="tok-k">=</span> <span class="tok-n">getRuntimeContext</span><span class="tok-o">.</span><span class="tok-n">getState</span><span class="tok-o">[</span><span class="tok-kt">Double</span><span class="tok-o">](</span><span class="tok-n">lastTempDescriptor</span><span class="tok-o">)</span>
  <span class="tok-o">}</span>

  <span class="tok-k">override</span> <span class="tok-k">def</span> <span class="tok-n">flatMap</span><span class="tok-o">(</span><span class="tok-n">reading</span><span class="tok-k">:</span> <span class="tok-kt">SensorReading</span><span class="tok-o">,</span>
                       <span class="tok-n">out</span><span class="tok-k">:</span> <span class="tok-kt">Collector</span><span class="tok-o">[(</span><span class="tok-kt">String</span>, <span class="tok-kt">Double</span>, <span class="tok-kt">Double</span><span class="tok-o">)])</span><span class="tok-k">:</span> <span class="tok-kt">Unit</span> <span class="tok-o">=</span> <span class="tok-o">{</span>
    <span class="tok-k">val</span> <span class="tok-n">lastTemp</span> <span class="tok-k">=</span> <span class="tok-n">lastTempState</span><span class="tok-o">.</span><span class="tok-n">value</span><span class="tok-o">()</span>
    <span class="tok-k">val</span> <span class="tok-n">tempDiff</span> <span class="tok-k">=</span> <span class="tok-o">(</span><span class="tok-n">reading</span><span class="tok-o">.</span><span class="tok-n">temperature</span> <span class="tok-o">-</span> <span class="tok-n">lastTemp</span><span class="tok-o">).</span><span class="tok-n">abs</span>
    <span class="tok-k">if</span> <span class="tok-o">(</span><span class="tok-n">tempDiff</span> <span class="tok-o">&gt;</span> <span class="tok-n">threshold</span><span class="tok-o">)</span> <span class="tok-o">{</span>
      <span class="tok-n">out</span><span class="tok-o">.</span><span class="tok-n">collect</span><span class="tok-o">((</span><span class="tok-n">reading</span><span class="tok-o">.</span><span class="tok-n">id</span><span class="tok-o">,</span> <span class="tok-n">reading</span><span class="tok-o">.</span><span class="tok-n">temperature</span><span class="tok-o">,</span> <span class="tok-n">tempDiff</span><span class="tok-o">))</span>
    <span class="tok-o">}</span>
    <span class="tok-k">this</span><span class="tok-o">.</span><span class="tok-n">lastTempState</span><span class="tok-o">.</span><span class="tok-n">update</span><span class="tok-o">(</span><span class="tok-n">reading</span><span class="tok-o">.</span><span class="tok-n">temperature</span><span class="tok-o">)</span>
  <span class="tok-o">}</span>
<span class="tok-o">}</span></code></pre>
</div>
</div>
<div class="paragraph">
<p>上面例子中的FlatMapFunction只能访问当前处理的元素所包含的key所对应的状态变量。</p>
</div>
<div class="admonitionblock note">
<table>
<tr>
<td class="icon">
<i class="fa icon-note" title="Note"></i>
</td>
<td class="content">
不同key对应的keyed state是相互隔离的。
</td>
</tr>
</table>
</div>
<div class="ulist">
<ul>
<li>
<p>通过RuntimeContext注册StateDescriptor。StateDescriptor以状态state的名字和存储的数据类型为参数。数据类型必须指定，因为Flink需要选择合适的序列化器。</p>
</li>
<li>
<p>在open()方法中创建state变量。注意复习之前的RichFunction相关知识。</p>
</li>
</ul>
</div>
<div class="paragraph">
<p>当一个函数注册了StateDescriptor描述符，Flink会检查状态后端是否已经存在这个状态。这种情况通常出现在应用挂掉要从检查点或者保存点恢复的时候。在这两种情况下，Flink会将注册的状态连接到已经存在的状态。如果不存在状态，则初始化一个空的状态。</p>
</div>
<div class="paragraph">
<p>使用FlatMap with keyed ValueState的快捷方式flatMapWithState也可以实现以上需求。</p>
</div>
<div class="listingblock">
<div class="title">Example 7-2. 使用flatMapWithState来实现需求</div>
<div class="content">
<pre class="pygments highlight"><code data-lang="scala"><span></span><span class="tok-k">val</span> <span class="tok-n">alerts</span><span class="tok-k">:</span> <span class="tok-kt">DataStream</span><span class="tok-o">[(</span><span class="tok-kt">String</span>, <span class="tok-kt">Double</span>, <span class="tok-kt">Double</span><span class="tok-o">)]</span> <span class="tok-k">=</span> <span class="tok-n">keyedSensorData</span>
  <span class="tok-o">.</span><span class="tok-n">flatMapWithState</span><span class="tok-o">[(</span><span class="tok-kt">String</span>, <span class="tok-kt">Double</span>, <span class="tok-kt">Double</span><span class="tok-o">)</span>, <span class="tok-kt">Double</span><span class="tok-o">]</span> <span class="tok-o">{</span>
    <span class="tok-k">case</span> <span class="tok-o">(</span><span class="tok-n">in</span><span class="tok-k">:</span> <span class="tok-kt">SensorReading</span><span class="tok-o">,</span> <span class="tok-nc">None</span><span class="tok-o">)</span> <span class="tok-k">=&gt;</span>
      <span class="tok-c1">// no previous temperature defined. Just update the last temperature</span>
      <span class="tok-o">(</span><span class="tok-nc">List</span><span class="tok-o">.</span><span class="tok-n">empty</span><span class="tok-o">,</span> <span class="tok-nc">Some</span><span class="tok-o">(</span><span class="tok-n">in</span><span class="tok-o">.</span><span class="tok-n">temperature</span><span class="tok-o">))</span>
    <span class="tok-k">case</span> <span class="tok-o">(</span><span class="tok-n">r</span><span class="tok-k">:</span> <span class="tok-kt">SensorReading</span><span class="tok-o">,</span> <span class="tok-n">lastTemp</span><span class="tok-k">:</span> <span class="tok-kt">Some</span><span class="tok-o">[</span><span class="tok-kt">Double</span><span class="tok-o">])</span> <span class="tok-k">=&gt;</span>
      <span class="tok-c1">// compare temperature difference with threshold</span>
      <span class="tok-k">val</span> <span class="tok-n">tempDiff</span> <span class="tok-k">=</span> <span class="tok-o">(</span><span class="tok-n">r</span><span class="tok-o">.</span><span class="tok-n">temperature</span> <span class="tok-o">-</span> <span class="tok-n">lastTemp</span><span class="tok-o">.</span><span class="tok-n">get</span><span class="tok-o">).</span><span class="tok-n">abs</span>
      <span class="tok-k">if</span> <span class="tok-o">(</span><span class="tok-n">tempDiff</span> <span class="tok-o">&gt;</span> <span class="tok-mf">1.7</span><span class="tok-o">)</span> <span class="tok-o">{</span>
        <span class="tok-c1">// threshold exceeded. Emit an alert and update the last temperature</span>
        <span class="tok-o">(</span><span class="tok-nc">List</span><span class="tok-o">((</span><span class="tok-n">r</span><span class="tok-o">.</span><span class="tok-n">id</span><span class="tok-o">,</span> <span class="tok-n">r</span><span class="tok-o">.</span><span class="tok-n">temperature</span><span class="tok-o">,</span> <span class="tok-n">tempDiff</span><span class="tok-o">)),</span> <span class="tok-nc">Some</span><span class="tok-o">(</span><span class="tok-n">r</span><span class="tok-o">.</span><span class="tok-n">temperature</span><span class="tok-o">))</span>
      <span class="tok-o">}</span> <span class="tok-k">else</span> <span class="tok-o">{</span>
        <span class="tok-c1">// threshold not exceeded. Just update the last temperature</span>
        <span class="tok-o">(</span><span class="tok-nc">List</span><span class="tok-o">.</span><span class="tok-n">empty</span><span class="tok-o">,</span> <span class="tok-nc">Some</span><span class="tok-o">(</span><span class="tok-n">r</span><span class="tok-o">.</span><span class="tok-n">temperature</span><span class="tok-o">))</span>
      <span class="tok-o">}</span>
  <span class="tok-o">}</span></code></pre>
</div>
</div>
</div>
<div class="sect3">
<h4 id="_使用listcheckpointed接口来实现操作符的列表状态list_state">7.1.2. 使用ListCheckpointed接口来实现操作符的列表状态(List State)</h4>
<div class="paragraph">
<p>操作符状态会在操作符的每一个并行实例中去维护。一个操作符并行实例上的所有事件都可以访问同一个状态。Flink支持三种操作符状态：list state, list union state, broadcast state。</p>
</div>
<div class="paragraph">
<p>一个函数可以实现ListCheckpointed接口来处理操作符的list state。ListCheckpointed接口无法处理ValueState和ListState，因为这些状态是注册在状态后端的。操作符状态类似于成员变量，和状态后端的交互通过ListCheckpointed接口的回调函数实现。接口提供了两个方法：</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="pygments highlight"><code data-lang="scala"><span></span><span class="tok-c1">// 返回函数状态的快照，返回值为列表</span>
<span class="tok-n">snapshotState</span><span class="tok-o">(</span><span class="tok-n">checkpointId</span><span class="tok-k">:</span> <span class="tok-kt">Long</span><span class="tok-o">,</span> <span class="tok-n">timestamp</span><span class="tok-k">:</span> <span class="tok-kt">Long</span><span class="tok-o">)</span><span class="tok-k">:</span> <span class="tok-kt">java.util.List</span><span class="tok-o">[</span><span class="tok-kt">T</span><span class="tok-o">]</span>
<span class="tok-c1">// 从列表恢复函数状态</span>
<span class="tok-n">restoreState</span><span class="tok-o">(</span><span class="tok-n">java</span><span class="tok-o">.</span><span class="tok-n">util</span><span class="tok-o">.</span><span class="tok-nc">List</span><span class="tok-o">[</span><span class="tok-kt">T</span><span class="tok-o">]</span> <span class="tok-n">state</span><span class="tok-o">)</span><span class="tok-k">:</span> <span class="tok-kt">Unit</span></code></pre>
</div>
</div>
<div class="paragraph">
<p>当Flink触发stateful functon的一次checkpoint时，snapshotState()方法会被调用。方法接收两个参数，checkpointId为唯一的单调递增的检查点Id，timestamp为当master机器开始做检查点操作时的墙上时钟（机器时间）。方法必须返回序列化好的状态对象的列表。</p>
</div>
<div class="paragraph">
<p>当宕机程序从检查点或者保存点恢复时会调用restoreState()方法。restoreState使用snapshotState保存的列表来恢复。</p>
</div>
<div class="paragraph">
<p>下面的例子展示了如何实现ListCheckpointed接口。业务场景为：一个对每一个并行实例的超过阈值的温度的计数程序。</p>
</div>
<div class="listingblock">
<div class="title">Example 7-3</div>
<div class="content">
<pre class="pygments highlight"><code data-lang="scala"><span></span><span class="tok-k">class</span> <span class="tok-nc">HighTempCounter</span><span class="tok-o">(</span><span class="tok-k">val</span> <span class="tok-n">threshold</span><span class="tok-k">:</span> <span class="tok-kt">Double</span><span class="tok-o">)</span>
    <span class="tok-k">extends</span> <span class="tok-nc">RichFlatMapFunction</span><span class="tok-o">[</span><span class="tok-kt">SensorReading</span>, <span class="tok-o">(</span><span class="tok-kt">Int</span>, <span class="tok-kt">Long</span><span class="tok-o">)]</span>
    <span class="tok-k">with</span> <span class="tok-nc">ListCheckpointed</span><span class="tok-o">[</span><span class="tok-kt">java.lang.Long</span><span class="tok-o">]</span> <span class="tok-o">{</span>

  <span class="tok-c1">// index of the subtask</span>
  <span class="tok-k">private</span> <span class="tok-k">lazy</span> <span class="tok-k">val</span> <span class="tok-n">subtaskIdx</span> <span class="tok-k">=</span> <span class="tok-n">getRuntimeContext</span>
    <span class="tok-o">.</span><span class="tok-n">getIndexOfThisSubtask</span>
  <span class="tok-c1">// local count variable</span>
  <span class="tok-k">private</span> <span class="tok-k">var</span> <span class="tok-n">highTempCnt</span> <span class="tok-k">=</span> <span class="tok-mi">0L</span>

  <span class="tok-k">override</span> <span class="tok-k">def</span> <span class="tok-n">flatMap</span><span class="tok-o">(</span>
      <span class="tok-n">in</span><span class="tok-k">:</span> <span class="tok-kt">SensorReading</span><span class="tok-o">,</span>
      <span class="tok-n">out</span><span class="tok-k">:</span> <span class="tok-kt">Collector</span><span class="tok-o">[(</span><span class="tok-kt">Int</span>, <span class="tok-kt">Long</span><span class="tok-o">)])</span><span class="tok-k">:</span> <span class="tok-kt">Unit</span> <span class="tok-o">=</span> <span class="tok-o">{</span>
    <span class="tok-k">if</span> <span class="tok-o">(</span><span class="tok-n">in</span><span class="tok-o">.</span><span class="tok-n">temperature</span> <span class="tok-o">&gt;</span> <span class="tok-n">threshold</span><span class="tok-o">)</span> <span class="tok-o">{</span>
      <span class="tok-c1">// increment counter if threshold is exceeded</span>
      <span class="tok-n">highTempCnt</span> <span class="tok-o">+=</span> <span class="tok-mi">1</span>
      <span class="tok-c1">// emit update with subtask index and counter</span>
      <span class="tok-n">out</span><span class="tok-o">.</span><span class="tok-n">collect</span><span class="tok-o">((</span><span class="tok-n">subtaskIdx</span><span class="tok-o">,</span> <span class="tok-n">highTempCnt</span><span class="tok-o">))</span>
    <span class="tok-o">}</span>
  <span class="tok-o">}</span>

  <span class="tok-k">override</span> <span class="tok-k">def</span> <span class="tok-n">restoreState</span><span class="tok-o">(</span>
      <span class="tok-n">state</span><span class="tok-k">:</span> <span class="tok-kt">util.List</span><span class="tok-o">[</span><span class="tok-kt">java.lang.Long</span><span class="tok-o">])</span><span class="tok-k">:</span> <span class="tok-kt">Unit</span> <span class="tok-o">=</span> <span class="tok-o">{</span>
    <span class="tok-n">highTempCnt</span> <span class="tok-k">=</span> <span class="tok-mi">0</span>
    <span class="tok-c1">// restore state by adding all longs of the list</span>
    <span class="tok-k">for</span> <span class="tok-o">(</span><span class="tok-n">cnt</span> <span class="tok-k">&lt;-</span> <span class="tok-n">state</span><span class="tok-o">.</span><span class="tok-n">asScala</span><span class="tok-o">)</span> <span class="tok-o">{</span>
      <span class="tok-n">highTempCnt</span> <span class="tok-o">+=</span> <span class="tok-n">cnt</span>
    <span class="tok-o">}</span>
  <span class="tok-o">}</span>

  <span class="tok-k">override</span> <span class="tok-k">def</span> <span class="tok-n">snapshotState</span><span class="tok-o">(</span>
      <span class="tok-n">chkpntId</span><span class="tok-k">:</span> <span class="tok-kt">Long</span><span class="tok-o">,</span>
      <span class="tok-n">ts</span><span class="tok-k">:</span> <span class="tok-kt">Long</span><span class="tok-o">)</span><span class="tok-k">:</span> <span class="tok-kt">java.util.List</span><span class="tok-o">[</span><span class="tok-kt">java.lang.Long</span><span class="tok-o">]</span> <span class="tok-k">=</span> <span class="tok-o">{</span>
    <span class="tok-c1">// snapshot state as list with a single count</span>
    <span class="tok-n">java</span><span class="tok-o">.</span><span class="tok-n">util</span><span class="tok-o">.</span><span class="tok-nc">Collections</span><span class="tok-o">.</span><span class="tok-n">singletonList</span><span class="tok-o">(</span><span class="tok-n">highTempCnt</span><span class="tok-o">)</span>
  <span class="tok-o">}</span>
<span class="tok-o">}</span></code></pre>
</div>
</div>
<div class="paragraph">
<p>上面的例子中，每一个并行实例都计数了本实例有多少温度值超过了设定的阈值。例子中使用了操作符状态，并且每一个并行实例都拥有自己的状态变量，这个状态变量将会被检查点操作保存下来，并且可以通过使用ListCheckpointed接口来恢复状态变量。</p>
</div>
<div class="paragraph">
<p>看了上面的例子，我们可能会有疑问，那就是为什么操作符状态是状态对象的列表。这是因为列表数据结构支持包含操作符状态的函数的并行度改变的操作。为了增加或者减少包含了操作符状态的函数的并行度，操作符状态需要被重新分区到更多或者更少的并行任务实例中去。而这样的操作需要合并或者分割状态对象。而对于每一个有状态的函数，分割和合并状态对象都是很常见的操作，所以这显然不是任何类型的状态都能自动完成的。</p>
</div>
<div class="paragraph">
<p>通过提供一个状态对象的列表，拥有操作符状态的函数可以使用snapshotState()方法和restoreState()方法来实现以上所说的逻辑。snapshotState()方法将操作符状态分割成多个部分，restoreState()方法从所有的部分中将状态对象收集起来。当函数的操作符状态恢复时，状态变量将被分区到函数的所有不同的并行实例中去，并作为参数传递给restoreState()方法。如果并行任务的数量大于状态对象的数量，那么一些并行任务在开始的时候是没有状态的，所以restoreState()函数的参数为空列表。</p>
</div>
<div class="paragraph">
<p>再来看一下上面的程序，我们可以看到操作符的每一个并行实例都暴露了一个状态对象的列表。如果我们增加操作符的并行度，那么一些并行任务将会从0开始计数。为了获得更好的状态分区的行为，当HighTempCounter函数扩容时，我们可以按照下面的程序来实现snapshotState()方法，这样就可以把计数值分配到不同的并行计数中去了。</p>
</div>
<div class="listingblock">
<div class="title">Example 7-4</div>
<div class="content">
<pre class="pygments highlight"><code data-lang="scala"><span></span><span class="tok-k">override</span> <span class="tok-k">def</span> <span class="tok-n">snapshotState</span><span class="tok-o">(</span>
    <span class="tok-n">chkpntId</span><span class="tok-k">:</span> <span class="tok-kt">Long</span><span class="tok-o">,</span>
    <span class="tok-n">ts</span><span class="tok-k">:</span> <span class="tok-kt">Long</span><span class="tok-o">)</span><span class="tok-k">:</span> <span class="tok-kt">java.util.List</span><span class="tok-o">[</span><span class="tok-kt">java.lang.Long</span><span class="tok-o">]</span> <span class="tok-k">=</span> <span class="tok-o">{</span>
  <span class="tok-c1">// split count into ten partial counts</span>
  <span class="tok-k">val</span> <span class="tok-n">div</span> <span class="tok-k">=</span> <span class="tok-n">highTempCnt</span> <span class="tok-o">/</span> <span class="tok-mi">10</span>
  <span class="tok-k">val</span> <span class="tok-n">mod</span> <span class="tok-k">=</span> <span class="tok-o">(</span><span class="tok-n">highTempCnt</span> <span class="tok-o">%</span> <span class="tok-mi">10</span><span class="tok-o">).</span><span class="tok-n">toInt</span>
  <span class="tok-c1">// return count as ten parts</span>
  <span class="tok-o">(</span><span class="tok-nc">List</span><span class="tok-o">.</span><span class="tok-n">fill</span><span class="tok-o">(</span><span class="tok-n">mod</span><span class="tok-o">)(</span><span class="tok-k">new</span> <span class="tok-n">java</span><span class="tok-o">.</span><span class="tok-n">lang</span><span class="tok-o">.</span><span class="tok-nc">Long</span><span class="tok-o">(</span><span class="tok-n">div</span> <span class="tok-o">+</span> <span class="tok-mi">1</span><span class="tok-o">))</span> <span class="tok-o">++</span>
    <span class="tok-nc">List</span><span class="tok-o">.</span><span class="tok-n">fill</span><span class="tok-o">(</span><span class="tok-mi">10</span> <span class="tok-o">-</span> <span class="tok-n">mod</span><span class="tok-o">)(</span><span class="tok-k">new</span> <span class="tok-n">java</span><span class="tok-o">.</span><span class="tok-n">lang</span><span class="tok-o">.</span><span class="tok-nc">Long</span><span class="tok-o">(</span><span class="tok-n">div</span><span class="tok-o">))).</span><span class="tok-n">asJava</span>
<span class="tok-o">}</span></code></pre>
</div>
</div>
</div>
<div class="sect3">
<h4 id="_使用连接的广播状态using_connected_broadcast_state">7.1.3. 使用连接的广播状态(using connected broadcast state)</h4>
<div class="paragraph">
<p>一个常见的需求就是流应用需要将同样的事件分发到操作符的所有的并行实例中，而这样的分发操作还得是可恢复的。</p>
</div>
<div class="paragraph">
<p>我们举个例子：一条流是一个规则(比如5秒钟内连续两个超过阈值的温度)，另一条流是待匹配的流。也就是说，规则流和事件流。所以每一个操作符的并行实例都需要把规则流保存在操作符状态中。也就是说，规则流需要被广播到所有的并行实例中去。</p>
</div>
<div class="paragraph">
<p>在Flink中，这样的状态叫做广播状态(broadcast state)。广播状态和DataStream或者KeyedStream都可以做连接操作。</p>
</div>
<div class="paragraph">
<p>下面的例子实现了一个温度报警应用，应用有可以动态设定的阈值，动态设定通过广播流来实现。</p>
</div>
<div class="listingblock">
<div class="title">Example 7-5</div>
<div class="content">
<pre class="pygments highlight"><code data-lang="scala"><span></span><span class="tok-k">val</span> <span class="tok-n">sensorData</span><span class="tok-k">:</span> <span class="tok-kt">DataStream</span><span class="tok-o">[</span><span class="tok-kt">SensorReading</span><span class="tok-o">]</span> <span class="tok-k">=</span> <span class="tok-o">???</span>
<span class="tok-k">val</span> <span class="tok-n">thresholds</span><span class="tok-k">:</span> <span class="tok-kt">DataStream</span><span class="tok-o">[</span><span class="tok-kt">ThresholdUpdate</span><span class="tok-o">]</span> <span class="tok-k">=</span> <span class="tok-o">???</span>
<span class="tok-k">val</span> <span class="tok-n">keyedSensorData</span><span class="tok-k">:</span> <span class="tok-kt">KeyedStream</span><span class="tok-o">[</span><span class="tok-kt">SensorReading</span>, <span class="tok-kt">String</span><span class="tok-o">]</span> <span class="tok-k">=</span> <span class="tok-n">sensorData</span><span class="tok-o">.</span><span class="tok-n">keyBy</span><span class="tok-o">(</span><span class="tok-k">_</span><span class="tok-o">.</span><span class="tok-n">id</span><span class="tok-o">)</span>

<span class="tok-c1">// the descriptor of the broadcast state</span>
<span class="tok-k">val</span> <span class="tok-n">broadcastStateDescriptor</span> <span class="tok-k">=</span>
  <span class="tok-k">new</span> <span class="tok-nc">MapStateDescriptor</span><span class="tok-o">[</span><span class="tok-kt">String</span>, <span class="tok-kt">Double</span><span class="tok-o">](</span>
    <span class="tok-s">&quot;thresholds&quot;</span><span class="tok-o">,</span> <span class="tok-n">classOf</span><span class="tok-o">[</span><span class="tok-kt">String</span><span class="tok-o">],</span> <span class="tok-n">classOf</span><span class="tok-o">[</span><span class="tok-kt">Double</span><span class="tok-o">])</span>

<span class="tok-k">val</span> <span class="tok-n">broadcastThresholds</span><span class="tok-k">:</span> <span class="tok-kt">BroadcastStream</span><span class="tok-o">[</span><span class="tok-kt">ThresholdUpdate</span><span class="tok-o">]</span> <span class="tok-k">=</span> <span class="tok-n">thresholds</span>
  <span class="tok-o">.</span><span class="tok-n">broadcast</span><span class="tok-o">(</span><span class="tok-n">broadcastStateDescriptor</span><span class="tok-o">)</span>

<span class="tok-c1">// connect keyed sensor stream and broadcasted rules stream</span>
<span class="tok-k">val</span> <span class="tok-n">alerts</span><span class="tok-k">:</span> <span class="tok-kt">DataStream</span><span class="tok-o">[(</span><span class="tok-kt">String</span>, <span class="tok-kt">Double</span>, <span class="tok-kt">Double</span><span class="tok-o">)]</span> <span class="tok-k">=</span> <span class="tok-n">keyedSensorData</span>
  <span class="tok-o">.</span><span class="tok-n">connect</span><span class="tok-o">(</span><span class="tok-n">broadcastThresholds</span><span class="tok-o">)</span>
  <span class="tok-o">.</span><span class="tok-n">process</span><span class="tok-o">(</span><span class="tok-k">new</span> <span class="tok-nc">UpdatableTemperatureAlertFunction</span><span class="tok-o">())</span></code></pre>
</div>
</div>
<div class="paragraph">
<p>带有广播状态的函数在应用到两条流上时分三个步骤：</p>
</div>
<div class="ulist">
<ul>
<li>
<p>调用DataStream.broadcast()来创建BroadcastStream，定义一个或者多个MapStateDescriptor对象。</p>
</li>
<li>
<p>将BroadcastStream和DataStream/KeyedStream做connect操作。</p>
</li>
<li>
<p>在connected streams上调用KeyedBroadcastProcessFunction/BroadcastProcessFunction。</p>
</li>
</ul>
</div>
<div class="paragraph">
<p>下面的例子实现了动态设定温度阈值的功能。</p>
</div>
<div class="listingblock">
<div class="title">Example 7-7</div>
<div class="content">
<pre class="pygments highlight"><code data-lang="scala"><span></span><span class="tok-k">class</span> <span class="tok-nc">UpdatableTemperatureAlertFunction</span><span class="tok-o">()</span>
    <span class="tok-k">extends</span> <span class="tok-nc">KeyedBroadcastProcessFunction</span>
      <span class="tok-o">[</span><span class="tok-kt">String</span>, <span class="tok-kt">SensorReading</span>, <span class="tok-kt">ThresholdUpdate</span>, <span class="tok-o">(</span><span class="tok-kt">String</span>, <span class="tok-kt">Double</span>, <span class="tok-kt">Double</span><span class="tok-o">)]</span> <span class="tok-o">{</span>

  <span class="tok-c1">// the descriptor of the broadcast state</span>
  <span class="tok-k">private</span> <span class="tok-k">lazy</span> <span class="tok-k">val</span> <span class="tok-n">thresholdStateDescriptor</span> <span class="tok-k">=</span>
    <span class="tok-k">new</span> <span class="tok-nc">MapStateDescriptor</span><span class="tok-o">[</span><span class="tok-kt">String</span>, <span class="tok-kt">Double</span><span class="tok-o">](</span>
      <span class="tok-s">&quot;thresholds&quot;</span><span class="tok-o">,</span> <span class="tok-n">classOf</span><span class="tok-o">[</span><span class="tok-kt">String</span><span class="tok-o">],</span> <span class="tok-n">classOf</span><span class="tok-o">[</span><span class="tok-kt">Double</span><span class="tok-o">])</span>

  <span class="tok-c1">// the keyed state handle</span>
  <span class="tok-k">private</span> <span class="tok-k">var</span> <span class="tok-n">lastTempState</span><span class="tok-k">:</span> <span class="tok-kt">ValueState</span><span class="tok-o">[</span><span class="tok-kt">Double</span><span class="tok-o">]</span> <span class="tok-k">=</span> <span class="tok-k">_</span>

  <span class="tok-k">override</span> <span class="tok-k">def</span> <span class="tok-n">open</span><span class="tok-o">(</span><span class="tok-n">parameters</span><span class="tok-k">:</span> <span class="tok-kt">Configuration</span><span class="tok-o">)</span><span class="tok-k">:</span> <span class="tok-kt">Unit</span> <span class="tok-o">=</span> <span class="tok-o">{</span>
    <span class="tok-c1">// create keyed state descriptor</span>
    <span class="tok-k">val</span> <span class="tok-n">lastTempDescriptor</span> <span class="tok-k">=</span> <span class="tok-k">new</span> <span class="tok-nc">ValueStateDescriptor</span><span class="tok-o">[</span><span class="tok-kt">Double</span><span class="tok-o">](</span>
      <span class="tok-s">&quot;lastTemp&quot;</span><span class="tok-o">,</span> <span class="tok-n">classOf</span><span class="tok-o">[</span><span class="tok-kt">Double</span><span class="tok-o">])</span>
    <span class="tok-c1">// obtain the keyed state handle</span>
    <span class="tok-n">lastTempState</span> <span class="tok-k">=</span> <span class="tok-n">getRuntimeContext</span><span class="tok-o">.</span><span class="tok-n">getState</span><span class="tok-o">[</span><span class="tok-kt">Double</span><span class="tok-o">](</span><span class="tok-n">lastTempDescriptor</span><span class="tok-o">)</span>
  <span class="tok-o">}</span>

  <span class="tok-k">override</span> <span class="tok-k">def</span> <span class="tok-n">processBroadcastElement</span><span class="tok-o">(</span>
      <span class="tok-n">update</span><span class="tok-k">:</span> <span class="tok-kt">ThresholdUpdate</span><span class="tok-o">,</span>
      <span class="tok-n">ctx</span><span class="tok-k">:</span> <span class="tok-kt">KeyedBroadcastProcessFunction</span>
        <span class="tok-o">[</span><span class="tok-kt">String</span>, <span class="tok-kt">SensorReading</span>, <span class="tok-kt">ThresholdUpdate</span>, <span class="tok-o">(</span><span class="tok-kt">String</span>, <span class="tok-kt">Double</span>, <span class="tok-kt">Double</span><span class="tok-o">)]</span><span class="tok-k">#</span><span class="tok-nc">Context</span><span class="tok-o">,</span>
      <span class="tok-n">out</span><span class="tok-k">:</span> <span class="tok-kt">Collector</span><span class="tok-o">[(</span><span class="tok-kt">String</span>, <span class="tok-kt">Double</span>, <span class="tok-kt">Double</span><span class="tok-o">)])</span><span class="tok-k">:</span> <span class="tok-kt">Unit</span> <span class="tok-o">=</span> <span class="tok-o">{</span>
    <span class="tok-c1">// get broadcasted state handle</span>
    <span class="tok-k">val</span> <span class="tok-n">thresholds</span> <span class="tok-k">=</span> <span class="tok-n">ctx</span><span class="tok-o">.</span><span class="tok-n">getBroadcastState</span><span class="tok-o">(</span><span class="tok-n">thresholdStateDescriptor</span><span class="tok-o">)</span>

    <span class="tok-k">if</span> <span class="tok-o">(</span><span class="tok-n">update</span><span class="tok-o">.</span><span class="tok-n">threshold</span> <span class="tok-o">!=</span> <span class="tok-mf">0.0d</span><span class="tok-o">)</span> <span class="tok-o">{</span>
      <span class="tok-c1">// configure a new threshold for the sensor</span>
      <span class="tok-n">thresholds</span><span class="tok-o">.</span><span class="tok-n">put</span><span class="tok-o">(</span><span class="tok-n">update</span><span class="tok-o">.</span><span class="tok-n">id</span><span class="tok-o">,</span> <span class="tok-n">update</span><span class="tok-o">.</span><span class="tok-n">threshold</span><span class="tok-o">)</span>
    <span class="tok-o">}</span> <span class="tok-k">else</span> <span class="tok-o">{</span>
      <span class="tok-c1">// remove threshold for the sensor</span>
      <span class="tok-n">thresholds</span><span class="tok-o">.</span><span class="tok-n">remove</span><span class="tok-o">(</span><span class="tok-n">update</span><span class="tok-o">.</span><span class="tok-n">id</span><span class="tok-o">)</span>
    <span class="tok-o">}</span>
  <span class="tok-o">}</span>

  <span class="tok-k">override</span> <span class="tok-k">def</span> <span class="tok-n">processElement</span><span class="tok-o">(</span>
      <span class="tok-n">reading</span><span class="tok-k">:</span> <span class="tok-kt">SensorReading</span><span class="tok-o">,</span>
      <span class="tok-n">readOnlyCtx</span><span class="tok-k">:</span> <span class="tok-kt">KeyedBroadcastProcessFunction</span>
        <span class="tok-o">[</span><span class="tok-kt">String</span>, <span class="tok-kt">SensorReading</span>, <span class="tok-kt">ThresholdUpdate</span>,
        <span class="tok-o">(</span><span class="tok-kt">String</span>, <span class="tok-kt">Double</span>, <span class="tok-kt">Double</span><span class="tok-o">)]</span><span class="tok-k">#</span><span class="tok-nc">ReadOnlyContext</span><span class="tok-o">,</span>
      <span class="tok-n">out</span><span class="tok-k">:</span> <span class="tok-kt">Collector</span><span class="tok-o">[(</span><span class="tok-kt">String</span>, <span class="tok-kt">Double</span>, <span class="tok-kt">Double</span><span class="tok-o">)])</span><span class="tok-k">:</span> <span class="tok-kt">Unit</span> <span class="tok-o">=</span> <span class="tok-o">{</span>
    <span class="tok-c1">// get read-only broadcast state</span>
    <span class="tok-k">val</span> <span class="tok-n">thresholds</span> <span class="tok-k">=</span> <span class="tok-n">readOnlyCtx</span><span class="tok-o">.</span><span class="tok-n">getBroadcastState</span><span class="tok-o">(</span><span class="tok-n">thresholdStateDescriptor</span><span class="tok-o">)</span>
    <span class="tok-c1">// check if we have a threshold</span>
    <span class="tok-k">if</span> <span class="tok-o">(</span><span class="tok-n">thresholds</span><span class="tok-o">.</span><span class="tok-n">contains</span><span class="tok-o">(</span><span class="tok-n">reading</span><span class="tok-o">.</span><span class="tok-n">id</span><span class="tok-o">))</span> <span class="tok-o">{</span>
      <span class="tok-c1">// get threshold for sensor</span>
      <span class="tok-k">val</span> <span class="tok-n">sensorThreshold</span><span class="tok-k">:</span> <span class="tok-kt">Double</span> <span class="tok-o">=</span> <span class="tok-n">thresholds</span><span class="tok-o">.</span><span class="tok-n">get</span><span class="tok-o">(</span><span class="tok-n">reading</span><span class="tok-o">.</span><span class="tok-n">id</span><span class="tok-o">)</span>

      <span class="tok-c1">// fetch the last temperature from state</span>
      <span class="tok-k">val</span> <span class="tok-n">lastTemp</span> <span class="tok-k">=</span> <span class="tok-n">lastTempState</span><span class="tok-o">.</span><span class="tok-n">value</span><span class="tok-o">()</span>
      <span class="tok-c1">// check if we need to emit an alert</span>
      <span class="tok-k">val</span> <span class="tok-n">tempDiff</span> <span class="tok-k">=</span> <span class="tok-o">(</span><span class="tok-n">reading</span><span class="tok-o">.</span><span class="tok-n">temperature</span> <span class="tok-o">-</span> <span class="tok-n">lastTemp</span><span class="tok-o">).</span><span class="tok-n">abs</span>
      <span class="tok-k">if</span> <span class="tok-o">(</span><span class="tok-n">tempDiff</span> <span class="tok-o">&gt;</span> <span class="tok-n">sensorThreshold</span><span class="tok-o">)</span> <span class="tok-o">{</span>
        <span class="tok-c1">// temperature increased by more than the threshold</span>
        <span class="tok-n">out</span><span class="tok-o">.</span><span class="tok-n">collect</span><span class="tok-o">((</span><span class="tok-n">reading</span><span class="tok-o">.</span><span class="tok-n">id</span><span class="tok-o">,</span> <span class="tok-n">reading</span><span class="tok-o">.</span><span class="tok-n">temperature</span><span class="tok-o">,</span> <span class="tok-n">tempDiff</span><span class="tok-o">))</span>
      <span class="tok-o">}</span>
    <span class="tok-o">}</span>

    <span class="tok-c1">// update lastTemp state</span>
    <span class="tok-k">this</span><span class="tok-o">.</span><span class="tok-n">lastTempState</span><span class="tok-o">.</span><span class="tok-n">update</span><span class="tok-o">(</span><span class="tok-n">reading</span><span class="tok-o">.</span><span class="tok-n">temperature</span><span class="tok-o">)</span>
  <span class="tok-o">}</span>
<span class="tok-o">}</span></code></pre>
</div>
</div>
</div>
</div>
<div class="sect2">
<h3 id="_配置检查点">7.2. 配置检查点</h3>
<div class="paragraph">
<p>10秒钟保存一次检查点。</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="pygments highlight"><code data-lang="scala"><span></span><span class="tok-k">val</span> <span class="tok-n">env</span> <span class="tok-k">=</span> <span class="tok-nc">StreamExecutionEnvironment</span><span class="tok-o">.</span><span class="tok-n">getExecutionEnvironment</span>

<span class="tok-c1">// set checkpointing interval to 10 seconds (10000 milliseconds)</span>
<span class="tok-n">env</span><span class="tok-o">.</span><span class="tok-n">enableCheckpointing</span><span class="tok-o">(</span><span class="tok-mi">10000L</span><span class="tok-o">)</span></code></pre>
</div>
</div>
<div class="sect3">
<h4 id="_将hdfs配置为状态后端">7.2.1. 将hdfs配置为状态后端</h4>
<div class="paragraph">
<p>首先在IDEA的pom文件中添加依赖：</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="pygments highlight"><code data-lang="xml"><span></span>		<span class="tok-nt">&lt;dependency&gt;</span>
			<span class="tok-nt">&lt;groupId&gt;</span>org.apache.hadoop<span class="tok-nt">&lt;/groupId&gt;</span>
			<span class="tok-nt">&lt;artifactId&gt;</span>hadoop-client<span class="tok-nt">&lt;/artifactId&gt;</span>
			<span class="tok-nt">&lt;version&gt;</span>2.8.3<span class="tok-nt">&lt;/version&gt;</span>
<span class="tok-c">&lt;!--			&lt;scope&gt;provided&lt;/scope&gt;--&gt;</span>
		<span class="tok-nt">&lt;/dependency&gt;</span></code></pre>
</div>
</div>
<div class="paragraph">
<p>在<code>hdfs-site.xml</code>添加:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="pygments highlight"><code data-lang="xml"><span></span>    <span class="tok-nt">&lt;property&gt;</span>
        <span class="tok-nt">&lt;name&gt;</span>dfs.permissions<span class="tok-nt">&lt;/name&gt;</span>
        <span class="tok-nt">&lt;value&gt;</span>false<span class="tok-nt">&lt;/value&gt;</span>
    <span class="tok-nt">&lt;/property&gt;</span></code></pre>
</div>
</div>
<div class="admonitionblock note">
<table>
<tr>
<td class="icon">
<i class="fa icon-note" title="Note"></i>
</td>
<td class="content">
别忘了重启hdfs文件系统！
</td>
</tr>
</table>
</div>
<div class="paragraph">
<p>然后添加本地文件夹和hdfs文件的映射：</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="pygments highlight"><code data-lang="shell"><span></span>hdfs getconf -confKey fs.default.name
hdfs dfs -put /home/parallels/flink/checkpoint hdfs://localhost:9000/flink</code></pre>
</div>
</div>
<div class="paragraph">
<p>然后在代码中添加：</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="pygments highlight"><code data-lang="scala"><span></span><span class="tok-n">env</span><span class="tok-o">.</span><span class="tok-n">enableCheckpointing</span><span class="tok-o">(</span><span class="tok-mi">5000</span><span class="tok-o">)</span>
<span class="tok-n">env</span><span class="tok-o">.</span><span class="tok-n">setStateBackend</span><span class="tok-o">(</span><span class="tok-k">new</span> <span class="tok-nc">FsStateBackend</span><span class="tok-o">(</span><span class="tok-s">&quot;hdfs://localhost:9000/flink&quot;</span><span class="tok-o">))</span></code></pre>
</div>
</div>
<div class="paragraph">
<p>检查一下检查点正确保存了没有：</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="pygments highlight"><code data-lang="shell"><span></span>hdfs dfs -ls hdfs://localhost:9000/flink</code></pre>
</div>
</div>
</div>
</div>
<div class="sect2">
<h3 id="_保证有状态应用的可维护性">7.3. 保证有状态应用的可维护性</h3>
<div class="sect3">
<h4 id="_指定唯一的操作符标识符operator_identifiers">7.3.1. 指定唯一的操作符标识符(operator identifiers)</h4>
<div class="paragraph">
<p>每一个操作符都可以指定唯一的标识符。标识符将会作为操作符的元数据和状态数据一起保存到savepoint中去。当应用从保存点恢复时，标识符可以用来在savepoint中查找标识符对应的操作符的状态数据。标识符必须是唯一的，否则应用不知道从哪一个标识符恢复。</p>
</div>
<div class="paragraph">
<p>强烈建议为应用的每一个操作符定义唯一标识符。例子：</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="pygments highlight"><code data-lang="scala"><span></span><span class="tok-k">val</span> <span class="tok-n">alerts</span><span class="tok-k">:</span> <span class="tok-kt">DataStream</span><span class="tok-o">[(</span><span class="tok-kt">String</span>, <span class="tok-kt">Double</span>, <span class="tok-kt">Double</span><span class="tok-o">)]</span> <span class="tok-k">=</span> <span class="tok-n">keyedSensorData</span>
  <span class="tok-o">.</span><span class="tok-n">flatMap</span><span class="tok-o">(</span><span class="tok-k">new</span> <span class="tok-nc">TemperatureAlertFunction</span><span class="tok-o">(</span><span class="tok-mf">1.1</span><span class="tok-o">))</span>
  <span class="tok-o">.</span><span class="tok-n">uid</span><span class="tok-o">(</span><span class="tok-s">&quot;TempAlert&quot;</span><span class="tok-o">)</span></code></pre>
</div>
</div>
</div>
<div class="sect3">
<h4 id="_指定操作符的最大并行度">7.3.2. 指定操作符的最大并行度</h4>
<div class="paragraph">
<p>操作符的最大并行度定义了操作符的keyed state可以被分到多少个key groups中。</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="pygments highlight"><code data-lang="scala"><span></span><span class="tok-k">val</span> <span class="tok-n">env</span> <span class="tok-k">=</span> <span class="tok-nc">StreamExecutionEnvironment</span><span class="tok-o">.</span><span class="tok-n">getExecutionEnvironment</span>

<span class="tok-c1">// set the maximum parallelism for this application</span>
<span class="tok-n">env</span><span class="tok-o">.</span><span class="tok-n">setMaxParallelism</span><span class="tok-o">(</span><span class="tok-mi">512</span><span class="tok-o">)</span>

<span class="tok-k">val</span> <span class="tok-n">alerts</span><span class="tok-k">:</span> <span class="tok-kt">DataStream</span><span class="tok-o">[(</span><span class="tok-kt">String</span>, <span class="tok-kt">Double</span>, <span class="tok-kt">Double</span><span class="tok-o">)]</span> <span class="tok-k">=</span> <span class="tok-n">keyedSensorData</span>
  <span class="tok-o">.</span><span class="tok-n">flatMap</span><span class="tok-o">(</span><span class="tok-k">new</span> <span class="tok-nc">TemperatureAlertFunction</span><span class="tok-o">(</span><span class="tok-mf">1.1</span><span class="tok-o">))</span>
  <span class="tok-c1">// set the maximum parallelism for this operator and</span>
  <span class="tok-c1">// override the application-wide value</span>
  <span class="tok-o">.</span><span class="tok-n">setMaxParallelism</span><span class="tok-o">(</span><span class="tok-mi">1024</span><span class="tok-o">)</span></code></pre>
</div>
</div>
</div>
</div>
<div class="sect2">
<h3 id="_有状态应用的性能和健壮性">7.4. 有状态应用的性能和健壮性</h3>
<div class="sect3">
<h4 id="_选择一个状态后端">7.4.1. 选择一个状态后端</h4>
<div class="ulist">
<ul>
<li>
<p>MemoryStateBackend将状态当作Java的对象(没有序列化操作)存储在TaskManager JVM进程的堆上。</p>
</li>
<li>
<p>FsStateBackend将状态存储在本地的文件系统或者远程的文件系统如HDFS。</p>
</li>
<li>
<p>RocksDBStateBackend将状态存储在RocksDB \footnote{Facebook开源的KV数据库} 中。</p>
</li>
</ul>
</div>
<div class="listingblock">
<div class="content">
<pre class="pygments highlight"><code data-lang="scala"><span></span><span class="tok-k">val</span> <span class="tok-n">env</span> <span class="tok-k">=</span> <span class="tok-nc">StreamExecutionEnvironment</span><span class="tok-o">.</span><span class="tok-n">getExecutionEnvironment</span>

<span class="tok-k">val</span> <span class="tok-n">checkpointPath</span><span class="tok-k">:</span> <span class="tok-kt">String</span> <span class="tok-o">=</span> <span class="tok-o">???</span>
<span class="tok-c1">// configure path for checkpoints on the remote filesystem</span>
<span class="tok-c1">// env.setStateBackend(new FsStateBackend(&quot;file:///tmp/checkpoints&quot;))</span>

<span class="tok-k">val</span> <span class="tok-n">backend</span> <span class="tok-k">=</span> <span class="tok-k">new</span> <span class="tok-nc">RocksDBStateBackend</span><span class="tok-o">(</span><span class="tok-n">checkpointPath</span><span class="tok-o">)</span>
<span class="tok-c1">// configure the state backend</span>
<span class="tok-n">env</span><span class="tok-o">.</span><span class="tok-n">setStateBackend</span><span class="tok-o">(</span><span class="tok-n">backend</span><span class="tok-o">)</span></code></pre>
</div>
</div>
</div>
<div class="sect3">
<h4 id="_防止状态泄露">7.4.2. 防止状态泄露</h4>
<div class="paragraph">
<p>流应用通常需要运行几个月或者几年。如果state数据不断增长的话，会爆炸。所以控制state数据的大小十分重要。而Flink并不会清理state和gc。所以所有的stateful operator都需要控制他们各自的状态数据大小，保证不爆炸。</p>
</div>
<div class="paragraph">
<p>例如我们之前讲过增量聚合函数ReduceFunction/AggregateFunction，就可以提前聚合而不给state太多压力。</p>
</div>
<div class="paragraph">
<p>我们来看一个例子，我们实现了一个KeyedProcessFunction，用来计算连续两次的温度的差值，如果差值超过阈值，报警。</p>
</div>
<div class="paragraph">
<p>我们之前实现过这个需求，但没有清理掉状态数据。比如一小时内不再产生温度数据的传感器对应的状态数据就可以清理掉了。</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="pygments highlight"><code data-lang="scala"><span></span><span class="tok-k">class</span> <span class="tok-nc">SelfCleaningTemperatureAlertFunction</span><span class="tok-o">(</span><span class="tok-k">val</span> <span class="tok-n">threshold</span><span class="tok-k">:</span> <span class="tok-kt">Double</span><span class="tok-o">)</span>
    <span class="tok-k">extends</span> <span class="tok-nc">KeyedProcessFunction</span><span class="tok-o">[</span><span class="tok-kt">String</span>, <span class="tok-kt">SensorReading</span>, <span class="tok-o">(</span><span class="tok-kt">String</span>, <span class="tok-kt">Double</span>, <span class="tok-kt">Double</span><span class="tok-o">)]</span> <span class="tok-o">{</span>

  <span class="tok-c1">// the keyed state handle for the last temperature</span>
  <span class="tok-k">private</span> <span class="tok-k">var</span> <span class="tok-n">lastTempState</span><span class="tok-k">:</span> <span class="tok-kt">ValueState</span><span class="tok-o">[</span><span class="tok-kt">Double</span><span class="tok-o">]</span> <span class="tok-k">=</span> <span class="tok-k">_</span>
  <span class="tok-c1">// the keyed state handle for the last registered timer</span>
  <span class="tok-k">private</span> <span class="tok-k">var</span> <span class="tok-n">lastTimerState</span><span class="tok-k">:</span> <span class="tok-kt">ValueState</span><span class="tok-o">[</span><span class="tok-kt">Long</span><span class="tok-o">]</span> <span class="tok-k">=</span> <span class="tok-k">_</span>

  <span class="tok-k">override</span> <span class="tok-k">def</span> <span class="tok-n">open</span><span class="tok-o">(</span><span class="tok-n">parameters</span><span class="tok-k">:</span> <span class="tok-kt">Configuration</span><span class="tok-o">)</span><span class="tok-k">:</span> <span class="tok-kt">Unit</span> <span class="tok-o">=</span> <span class="tok-o">{</span>
    <span class="tok-c1">// register state for last temperature</span>
    <span class="tok-k">val</span> <span class="tok-n">lastTempDesc</span> <span class="tok-k">=</span> <span class="tok-k">new</span> <span class="tok-nc">ValueStateDescriptor</span><span class="tok-o">[</span><span class="tok-kt">Double</span><span class="tok-o">](</span><span class="tok-s">&quot;lastTemp&quot;</span><span class="tok-o">,</span> <span class="tok-n">classOf</span><span class="tok-o">[</span><span class="tok-kt">Double</span><span class="tok-o">])</span>
    <span class="tok-n">lastTempState</span> <span class="tok-k">=</span> <span class="tok-n">getRuntimeContext</span><span class="tok-o">.</span><span class="tok-n">getState</span><span class="tok-o">[</span><span class="tok-kt">Double</span><span class="tok-o">](</span><span class="tok-n">lastTempDescriptor</span><span class="tok-o">)</span>
    <span class="tok-c1">// register state for last timer</span>
    <span class="tok-k">val</span> <span class="tok-n">lastTimerDesc</span> <span class="tok-k">=</span> <span class="tok-k">new</span> <span class="tok-nc">ValueStateDescriptor</span><span class="tok-o">[</span><span class="tok-kt">Long</span><span class="tok-o">](</span><span class="tok-s">&quot;lastTimer&quot;</span><span class="tok-o">,</span> <span class="tok-n">classOf</span><span class="tok-o">[</span><span class="tok-kt">Long</span><span class="tok-o">])</span>
    <span class="tok-n">lastTimerState</span> <span class="tok-k">=</span> <span class="tok-n">getRuntimeContext</span><span class="tok-o">.</span><span class="tok-n">getState</span><span class="tok-o">(</span><span class="tok-n">timestampDescriptor</span><span class="tok-o">)</span>
  <span class="tok-o">}</span>

  <span class="tok-k">override</span> <span class="tok-k">def</span> <span class="tok-n">processElement</span><span class="tok-o">(</span>
      <span class="tok-n">reading</span><span class="tok-k">:</span> <span class="tok-kt">SensorReading</span><span class="tok-o">,</span>
      <span class="tok-n">ctx</span><span class="tok-k">:</span> <span class="tok-kt">KeyedProcessFunction</span>
        <span class="tok-o">[</span><span class="tok-kt">String</span>, <span class="tok-kt">SensorReading</span>, <span class="tok-o">(</span><span class="tok-kt">String</span>, <span class="tok-kt">Double</span>, <span class="tok-kt">Double</span><span class="tok-o">)]</span><span class="tok-k">#</span><span class="tok-nc">Context</span><span class="tok-o">,</span>
      <span class="tok-n">out</span><span class="tok-k">:</span> <span class="tok-kt">Collector</span><span class="tok-o">[(</span><span class="tok-kt">String</span>, <span class="tok-kt">Double</span>, <span class="tok-kt">Double</span><span class="tok-o">)])</span><span class="tok-k">:</span> <span class="tok-kt">Unit</span> <span class="tok-o">=</span> <span class="tok-o">{</span>

    <span class="tok-c1">// compute timestamp of new clean up timer as record timestamp + one hour</span>
    <span class="tok-k">val</span> <span class="tok-n">newTimer</span> <span class="tok-k">=</span> <span class="tok-n">ctx</span><span class="tok-o">.</span><span class="tok-n">timestamp</span><span class="tok-o">()</span> <span class="tok-o">+</span> <span class="tok-o">(</span><span class="tok-mi">3600</span> <span class="tok-o">*</span> <span class="tok-mi">1000</span><span class="tok-o">)</span>
    <span class="tok-c1">// get timestamp of current timer</span>
    <span class="tok-k">val</span> <span class="tok-n">curTimer</span> <span class="tok-k">=</span> <span class="tok-n">lastTimerState</span><span class="tok-o">.</span><span class="tok-n">value</span><span class="tok-o">()</span>
    <span class="tok-c1">// delete previous timer and register new timer</span>
    <span class="tok-n">ctx</span><span class="tok-o">.</span><span class="tok-n">timerService</span><span class="tok-o">().</span><span class="tok-n">deleteEventTimeTimer</span><span class="tok-o">(</span><span class="tok-n">curTimer</span><span class="tok-o">)</span>
    <span class="tok-n">ctx</span><span class="tok-o">.</span><span class="tok-n">timerService</span><span class="tok-o">().</span><span class="tok-n">registerEventTimeTimer</span><span class="tok-o">(</span><span class="tok-n">newTimer</span><span class="tok-o">)</span>
    <span class="tok-c1">// update timer timestamp state</span>
    <span class="tok-n">lastTimerState</span><span class="tok-o">.</span><span class="tok-n">update</span><span class="tok-o">(</span><span class="tok-n">newTimer</span><span class="tok-o">)</span>

    <span class="tok-c1">// fetch the last temperature from state</span>
    <span class="tok-k">val</span> <span class="tok-n">lastTemp</span> <span class="tok-k">=</span> <span class="tok-n">lastTempState</span><span class="tok-o">.</span><span class="tok-n">value</span><span class="tok-o">()</span>
    <span class="tok-c1">// check if we need to emit an alert</span>
    <span class="tok-k">val</span> <span class="tok-n">tempDiff</span> <span class="tok-k">=</span> <span class="tok-o">(</span><span class="tok-n">reading</span><span class="tok-o">.</span><span class="tok-n">temperature</span> <span class="tok-o">-</span> <span class="tok-n">lastTemp</span><span class="tok-o">).</span><span class="tok-n">abs</span>
    <span class="tok-k">if</span> <span class="tok-o">(</span><span class="tok-n">tempDiff</span> <span class="tok-o">&gt;</span> <span class="tok-n">threshold</span><span class="tok-o">)</span> <span class="tok-o">{</span>
      <span class="tok-c1">// temperature increased by more than the threshold</span>
      <span class="tok-n">out</span><span class="tok-o">.</span><span class="tok-n">collect</span><span class="tok-o">((</span><span class="tok-n">reading</span><span class="tok-o">.</span><span class="tok-n">id</span><span class="tok-o">,</span> <span class="tok-n">reading</span><span class="tok-o">.</span><span class="tok-n">temperature</span><span class="tok-o">,</span> <span class="tok-n">tempDiff</span><span class="tok-o">))</span>
    <span class="tok-o">}</span>

    <span class="tok-c1">// update lastTemp state</span>
    <span class="tok-k">this</span><span class="tok-o">.</span><span class="tok-n">lastTempState</span><span class="tok-o">.</span><span class="tok-n">update</span><span class="tok-o">(</span><span class="tok-n">reading</span><span class="tok-o">.</span><span class="tok-n">temperature</span><span class="tok-o">)</span>
  <span class="tok-o">}</span>

  <span class="tok-k">override</span> <span class="tok-k">def</span> <span class="tok-n">onTimer</span><span class="tok-o">(</span>
      <span class="tok-n">timestamp</span><span class="tok-k">:</span> <span class="tok-kt">Long</span><span class="tok-o">,</span>
      <span class="tok-n">ctx</span><span class="tok-k">:</span> <span class="tok-kt">KeyedProcessFunction</span>
        <span class="tok-o">[</span><span class="tok-kt">String</span>, <span class="tok-kt">SensorReading</span>, <span class="tok-o">(</span><span class="tok-kt">String</span>, <span class="tok-kt">Double</span>, <span class="tok-kt">Double</span><span class="tok-o">)]</span><span class="tok-k">#</span><span class="tok-nc">OnTimerContext</span><span class="tok-o">,</span>
      <span class="tok-n">out</span><span class="tok-k">:</span> <span class="tok-kt">Collector</span><span class="tok-o">[(</span><span class="tok-kt">String</span>, <span class="tok-kt">Double</span>, <span class="tok-kt">Double</span><span class="tok-o">)])</span><span class="tok-k">:</span> <span class="tok-kt">Unit</span> <span class="tok-o">=</span> <span class="tok-o">{</span>

    <span class="tok-c1">// clear all state for the key</span>
    <span class="tok-n">lastTempState</span><span class="tok-o">.</span><span class="tok-n">clear</span><span class="tok-o">()</span>
    <span class="tok-n">lastTimerState</span><span class="tok-o">.</span><span class="tok-n">clear</span><span class="tok-o">()</span>
  <span class="tok-o">}</span>
<span class="tok-o">}</span></code></pre>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="sect1">
<h2 id="_从外部系统读取以及写入外部系统">8. 从外部系统读取以及写入外部系统</h2>
<div class="sectionbody">
<div class="paragraph">
<p>数据可以存储在不同的系统中，例如：文件系统，对象存储系统（OSS），关系型数据库，Key-Value存储，搜索引擎索引，日志系统，消息队列，等等。每一种系统都是给特定的应用场景设计的，在某一个特定的目标上超越了其他系统。今天的数据架构，往往包含着很多不同的存储系统。在将一个组件加入到我们的系统中时，我们需要问一个问题：“这个组件和架构中的其他组件能多好的一起工作？”</p>
</div>
<div class="paragraph">
<p>添加一个像Flink这样的数据处理系统，需要仔细的考虑。因为Flink没有自己的存储层，而是读取数据和持久化数据都需要依赖外部存储。所以，对于Flink，针对外部系统提供良好的读取和写入的连接器就很重要了。尽管如此，仅仅能够读写外部系统对于Flink这样想要提供任务故障情况下一致性保证的流处理器来讲，是不够的。</p>
</div>
<div class="paragraph">
<p>在本章中，我们将会讨论source和sink的连接器。这些连接器影响了Flink的一致性保证，也提供了对于最流行的一些外部系统的读写的连接器。我们还将学习如何实现自定义source和sink连接器，以及如何实现可以向外部系统发送异步读写请求的函数。</p>
</div>
<div class="sect2">
<h3 id="_应用的一致性保证">8.1. 应用的一致性保证</h3>
<div class="paragraph">
<p>Flink的检查点和恢复机制定期的会保存应用程序状态的一致性检查点。在故障的情况下，应用程序的状态将会从最近一次完成的检查点恢复，并继续处理。尽管如此，可以使用检查点来重置应用程序的状态无法完全达到令人满意的一致性保证。相反，source和sink的连接器需要和Flink的检查点和恢复机制进行集成才能提供有意义的一致性保证。</p>
</div>
<div class="paragraph">
<p>为了给应用程序提供恰好处理一次语义的状态一致性保证，应用程序的source连接器需要能够将source的读位置重置到之前保存的检查点位置。当处理一次检查点时，source操作符将会把source的读位置持久化，并在恢复的时候从这些读位置开始重新读取。支持读位置的检查点的source连接器一般来说是基于文件的存储系统，如：文件流或者Kafka source（检查点会持久化某个正在消费的topic的读偏移量）。如果一个应用程序从一个无法存储和重置读位置的source连接器摄入数据，那么当任务出现故障的时候，数据就会丢失。也就是说我们只能提供at-most-once）的一致性保证。</p>
</div>
<div class="paragraph">
<p>Fink的检查点和恢复机制和可以重置读位置的source连接器结合使用，可以保证应用程序不会丢失任何数据。尽管如此，应用程序可能会发出两次计算结果，因为从上一次检查点恢复的应用程序所计算的结果将会被重新发送一次（一些结果已经发送出去了，这时任务故障，然后从上一次检查点恢复，这些结果将被重新计算一次然后发送出去）。所以，可重置读位置的source和Flink的恢复机制不足以提供端到端的恰好处理一次语义，即使应用程序的状态是恰好处理一次一致性级别。</p>
</div>
<div class="paragraph">
<p>一个志在提供端到端恰好处理一次语义一致性的应用程序需要特殊的sink连接器。sink连接器可以在不同的情况下使用两种技术来达到恰好处理一次一致性语义：幂等性写入和事务性写入。</p>
</div>
<div class="sect3">
<h4 id="_幂等性写入">8.1.1. 幂等性写入</h4>
<div class="paragraph">
<p>一个幂等操作无论执行多少次都会返回同样的结果。例如，重复的向hashmap中插入同样的key-value对就是幂等操作，因为头一次插入操作之后所有的插入操作都不会改变这个hashmap，因为hashmap已经包含这个key-value对了。另一方面，append操作就不是幂等操作了，因为多次append同一个元素将会导致列表每次都会添加一个元素。在流处理程序中，幂等写入操作是很有意思的，因为幂等写入操作可以执行多次但不改变结果。所以它们可以在某种程度上缓和Flink检查点机制带来的重播计算结果的效应。</p>
</div>
<div class="paragraph">
<p>需要注意的是，依赖于幂等性sink来达到exactly-once语义的应用程序，必须保证在从检查点恢复以后，它将会覆盖之前已经写入的结果。例如，一个包含有sink操作的应用在sink到一个key-value存储时必须保证它能够确定的计算出将要更新的key值。同时，从Flink程序sink到的key-value存储中读取数据的应用，在Flink从检查点恢复的过程中，可能会看到不想看到的结果。当重播开始时，之前已经发出的计算结果可能会被更早的结果所覆盖（因为在恢复过程中）。所以，一个消费Flink程序输出数据的应用，可能会观察到时间回退，例如读到了比之前小的计数。也就是说，当流处理程序处于恢复过程中时，流处理程序的结果将处于不稳定的状态，因为一些结果被覆盖掉，而另一些结果还没有被覆盖。一旦重播完成，也就是说应用程序已经通过了之前出故障的点，结果将会继续保持一致性。</p>
</div>
</div>
<div class="sect3">
<h4 id="_事务性写入">8.1.2. 事务性写入</h4>
<div class="paragraph">
<p>第二种实现端到端的恰好处理一次一致性语义的方法基于事务性写入。其思想是只将最近一次成功保存的检查点之前的计算结果写入到外部系统中去。这样就保证了在任务故障的情况下，端到端恰好处理一次语义。应用将被重置到最近一次的检查点，而在这个检查点之后并没有向外部系统发出任何计算结果。通过只有当检查点保存完成以后再写入数据这种方法，事务性的方法将不会遭受幂等性写入所遭受的重播不一致的问题。尽管如此，事务性写入却带来了延迟，因为只有在检查点完成以后，我们才能看到计算结果。</p>
</div>
<div class="paragraph">
<p>Flink提供了两种构建模块来实现事务性sink连接器：write-ahead-log（WAL，预写式日志）sink和两阶段提交sink。WAL式sink将会把所有计算结果写入到应用程序的状态中，等接到检查点完成的通知，才会将计算结果发送到sink系统。因为sink操作会把数据都缓存在状态后段，所以WAL可以使用在任何外部sink系统上。尽管如此，WAL还是无法提供刀枪不入的恰好处理一次语义的保证，再加上由于要缓存数据带来的状态后段的状态大小的问题，WAL模型并不十分完美。</p>
</div>
<div class="paragraph">
<p>与之形成对比的，2PC sink需要sink系统提供事务的支持或者可以模拟出事务特性的模块。对于每一个检查点，sink开始一个事务，然后将所有的接收到的数据都添加到事务中，并将这些数据写入到sink系统，但并没有提交（commit）它们。当事务接收到检查点完成的通知时，事务将被commit，数据将被真正的写入sink系统。这项机制主要依赖于一次sink可以在检查点完成之前开始事务，并在应用程序从一次故障中恢复以后再commit的能力。</p>
</div>
<div class="paragraph">
<p>2PC协议依赖于Flink的检查点机制。检查点屏障是开始一个新的事务的通知，所有操作符自己的检查点成功的通知是它们可以commit的投票，而JobManager通知一个检查点成功的消息是commit事务的指令。于WAL sink形成对比的是，2PC sinks依赖于sink系统和sink本身的实现可以实现恰好处理一次语义。更多的，2PC sink不断的将数据写入到sink系统中，而WAL写模型就会有之前所述的问题。</p>
</div>
<table class="tableblock frame-all grid-all stretch">
<caption class="title">Table 1. 表格8-1</caption>
<colgroup>
<col style="width: 33.3333%;">
<col style="width: 33.3333%;">
<col style="width: 33.3334%;">
</colgroup>
<thead>
<tr>
<th class="tableblock halign-left valign-top"></th>
<th class="tableblock halign-left valign-top">不可重置的源</th>
<th class="tableblock halign-left valign-top">可重置的源</th>
</tr>
</thead>
<tbody>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock">any sink</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">at-most-once</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">at-least-once</p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock">幂等性sink</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">at-most-once</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">exactly-once(当从任务失败中恢复时，存在暂时的不一致性)</p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock">预写式日志sink</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">at-most-once</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">at-least-once</p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock">2PC sink</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">at-most-once</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">exactly-once</p></td>
</tr>
</tbody>
</table>
</div>
</div>
<div class="sect2">
<h3 id="_flink提供的连接器">8.2. Flink提供的连接器</h3>
<div class="paragraph">
<p>Flink提供了读写很多存储系统的连接器。消息队列，日志系统，例如Apache Kafka, Kinesis, RabbitMQ等等这些是常用的数据源。在批处理环境中，数据流很可能是监听一个文件系统，而当新的数据落盘的时候，读取这些新数据。</p>
</div>
<div class="paragraph">
<p>在sink一端，数据流经常写入到消息队列中，以供接下来的流处理程序消费。数据流也可能写入到文件系统中做持久化，或者交给批处理程序来进行分析。数据流还可能被写入到key-value存储或者关系型数据库中，例如Cassandra，ElasticSearch或者MySQL中，这样数据可供查询，还可以在仪表盘中显示出来。</p>
</div>
<div class="paragraph">
<p>不幸的是，对于大多数存储系统并没有标准接口，除了针对DBMS的JDBC。相反，每一个存储系统都需要有自己的特定的连接器。所以，Flink需要维护针对不同存储系统（消息队列，日志系统，文件系统，k-v数据库，关系型数据库等等）的连接器实现。</p>
</div>
<div class="paragraph">
<p>Flink提供了针对Apache Kafka, Kinesis, RabbitMQ, Apache Nifi, 各种文件系统，Cassandra, Elasticsearch, 还有JDBC的连接器。除此之外，Apache Bahir项目还提供了额外的针对例如ActiveMQ, Akka, Flume, Netty, 和Redis等的连接器。</p>
</div>
<div class="sect3">
<h4 id="_apache_kafka_source连接器">8.2.1. Apache Kafka Source连接器</h4>
<div class="paragraph">
<p>Apache Kafka是一个分布式流式平台。它的核心是一个分布式的发布订阅消息系统。</p>
</div>
<div class="paragraph">
<p>Kafka将事件流组织为所谓的topics。一个主题就是一个事件日志系统，Kafka可以保证主题中的数据在被读取时和这些数据在被写入时相同的顺序。为了扩大读写的规模，主题可以分裂为多个分区，这些分区分布在一个集群上面。这时，读写顺序的保证就限制到了分区这个粒度， Kafka并没有提供从不同分区读取数据时的顺序保证。Kafka分区的读位置称为偏移量（offset）。</p>
</div>
<div class="paragraph">
<p>Kafka的依赖引入如下：</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="pygments highlight"><code data-lang="xml"><span></span><span class="tok-nt">&lt;dependency&gt;</span>
   <span class="tok-nt">&lt;groupId&gt;</span>org.apache.flink<span class="tok-nt">&lt;/groupId&gt;</span>
   <span class="tok-nt">&lt;artifactId&gt;</span>flink-connector-kafka_2.12<span class="tok-nt">&lt;/artifactId&gt;</span>
   <span class="tok-nt">&lt;version&gt;</span>1.7.1<span class="tok-nt">&lt;/version&gt;</span>
<span class="tok-nt">&lt;/dependency&gt;</span></code></pre>
</div>
</div>
<div class="paragraph">
<p>Flink Kafka连接器并行的摄入事件流。每一个并行source任务可以从一个或者多个分区中读取数据。任务将会跟踪每一个分区当前的读偏移量，然后将读偏移量写入到检查点数据中。当从任务故障恢复时，读偏移量将被恢复，而source任务将从检查点保存的读偏移量开始重新读取数据。Flink Kafka连接器并不依赖Kafka自己的offset-tracking机制（基于消费者组实现）。下图展示了分区如何分配给source实例。</p>
</div>
<div class="imageblock">
<div class="content">
<img src="images/spaf_0801.png" alt="spaf 0801">
</div>
</div>
<div class="paragraph">
<p>Kafka source连接器使用如下代码创建</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="pygments highlight"><code data-lang="scala"><span></span><span class="tok-k">val</span> <span class="tok-n">properties</span> <span class="tok-k">=</span> <span class="tok-k">new</span> <span class="tok-nc">Properties</span><span class="tok-o">()</span>
<span class="tok-n">properties</span><span class="tok-o">.</span><span class="tok-n">setProperty</span><span class="tok-o">(</span><span class="tok-s">&quot;bootstrap.servers&quot;</span><span class="tok-o">,</span> <span class="tok-s">&quot;localhost:9092&quot;</span><span class="tok-o">)</span>
<span class="tok-n">properties</span><span class="tok-o">.</span><span class="tok-n">setProperty</span><span class="tok-o">(</span><span class="tok-s">&quot;group.id&quot;</span><span class="tok-o">,</span> <span class="tok-s">&quot;test&quot;</span><span class="tok-o">)</span>

<span class="tok-k">val</span> <span class="tok-n">stream</span><span class="tok-k">:</span> <span class="tok-kt">DataStream</span><span class="tok-o">[</span><span class="tok-kt">String</span><span class="tok-o">]</span> <span class="tok-k">=</span> <span class="tok-n">env</span><span class="tok-o">.</span><span class="tok-n">addSource</span><span class="tok-o">(</span>
  <span class="tok-k">new</span> <span class="tok-nc">FlinkKafkaConsumer</span><span class="tok-o">[</span><span class="tok-kt">String</span><span class="tok-o">](</span>
    <span class="tok-s">&quot;topic&quot;</span><span class="tok-o">,</span>
    <span class="tok-k">new</span> <span class="tok-nc">SimpleStringSchema</span><span class="tok-o">(),</span>
    <span class="tok-n">properties</span><span class="tok-o">))</span></code></pre>
</div>
</div>
<div class="paragraph">
<p>构造器接受三个参数。第一个参数定义了从哪些topic中读取数据，可以是一个topic，也可以是topic列表，还可以是匹配所有想要读取的topic的正则表达式。当从多个topic中读取数据时，Kafka连接器将会处理所有topic的分区，将这些分区的数据放到一条流中去。</p>
</div>
<div class="paragraph">
<p>第二个参数是一个DeserializationSchema或者KeyedDeserializationSchema。Kafka消息被存储为原始的字节数据，所以需要反序列化成Java或者Scala对象。上例中使用的SimpleStringSchema，是一个内置的DeserializationSchema，它仅仅是简单的将字节数组反序列化成字符串。DeserializationSchema和KeyedDeserializationSchema是公共的接口，所以我们可以自定义反序列化逻辑。</p>
</div>
<div class="paragraph">
<p>第三个参数是一个Properties对象，设置了用来读写的Kafka客户端的一些属性。</p>
</div>
<div class="paragraph">
<p>为了抽取事件时间的时间戳然后产生水印，我们可以通过调用FlinkKafkaConsumer.assignTimestampsAndWatermark()方法为Kafka消费者提供AssignerWithPeriodicWatermark或者AssignerWithPucntuatedWatermark。每一个assigner都将被应用到每个分区，来利用每一个分区的顺序保证特性。souce实例将会根据水印的传播协议聚合所有分区的水印。</p>
</div>
</div>
<div class="sect3">
<h4 id="_apache_kafka_sink连接器">8.2.2. Apache Kafka Sink连接器</h4>
<div class="paragraph">
<p>添加依赖：</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="pygments highlight"><code data-lang="xml"><span></span><span class="tok-nt">&lt;dependency&gt;</span>
   <span class="tok-nt">&lt;groupId&gt;</span>org.apache.flink<span class="tok-nt">&lt;/groupId&gt;</span>
   <span class="tok-nt">&lt;artifactId&gt;</span>flink-connector-kafka_2.12<span class="tok-nt">&lt;/artifactId&gt;</span>
   <span class="tok-nt">&lt;version&gt;</span>1.7.1<span class="tok-nt">&lt;/version&gt;</span>
<span class="tok-nt">&lt;/dependency&gt;</span></code></pre>
</div>
</div>
<div class="paragraph">
<p>下面的例子展示了如何创建一个Kafka sink</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="pygments highlight"><code data-lang="scala"><span></span><span class="tok-k">val</span> <span class="tok-n">stream</span><span class="tok-k">:</span> <span class="tok-kt">DataStream</span><span class="tok-o">[</span><span class="tok-kt">String</span><span class="tok-o">]</span> <span class="tok-k">=</span> <span class="tok-o">...</span>

<span class="tok-k">val</span> <span class="tok-n">myProducer</span> <span class="tok-k">=</span> <span class="tok-k">new</span> <span class="tok-nc">FlinkKafkaProducer</span><span class="tok-o">[</span><span class="tok-kt">String</span><span class="tok-o">](</span>
  <span class="tok-s">&quot;localhost:9092&quot;</span><span class="tok-o">,</span>         <span class="tok-c1">// broker list</span>
  <span class="tok-s">&quot;topic&quot;</span><span class="tok-o">,</span>                  <span class="tok-c1">// target topic</span>
  <span class="tok-k">new</span> <span class="tok-nc">SimpleStringSchema</span><span class="tok-o">)</span>   <span class="tok-c1">// serialization schema</span>

<span class="tok-n">stream</span><span class="tok-o">.</span><span class="tok-n">addSink</span><span class="tok-o">(</span><span class="tok-n">myProducer</span><span class="tok-o">)</span></code></pre>
</div>
</div>
</div>
<div class="sect3">
<h4 id="_kakfa_sink的at_least_once保证">8.2.3. Kakfa Sink的at-least-once保证</h4>
<div class="paragraph">
<p>Flink的Kafka sink提供了基于配置的一致性保证。Kafka sink使用下面的条件提供了至少处理一次保证：</p>
</div>
<div class="ulist">
<ul>
<li>
<p>Flink检查点机制开启，所有的数据源都是可重置的。</p>
</li>
<li>
<p>当写入失败时，sink连接器将会抛出异常，使得应用程序挂掉然后重启。这是默认行为。应用程序内部的Kafka客户端还可以配置为重试写入，只要提前声明当写入失败时，重试几次这样的属性（retries property）。</p>
</li>
<li>
<p>sink连接器在完成它的检查点之前会等待Kafka发送已经将数据写入的通知。</p>
</li>
</ul>
</div>
</div>
<div class="sect3">
<h4 id="_kafka_sink的恰好处理一次语义保证">8.2.4. Kafka Sink的恰好处理一次语义保证</h4>
<div class="paragraph">
<p>Kafka 0.11版本引入了事务写特性。由于这个新特性，Flink Kafka sink可以为输出结果提供恰好处理一次语义的一致性保证，只要经过合适的配置就行。Flink程序必须开启检查点机制，并从可重置的数据源进行消费。FlinkKafkaProducer还提供了包含Semantic参数的构造器来控制sink提供的一致性保证。可能的取值如下：</p>
</div>
<div class="ulist">
<ul>
<li>
<p>Semantic.NONE，不提供任何一致性保证。数据可能丢失或者被重写多次。</p>
</li>
<li>
<p>Semantic.AT_LEAST_ONCE，保证无数据丢失，但可能被处理多次。这个是默认设置。</p>
</li>
<li>
<p>Semantic.EXACTLY_ONCE，基于Kafka的事务性写入特性实现，保证每条数据恰好处理一次。</p>
</li>
</ul>
</div>
</div>
<div class="sect3">
<h4 id="_文件系统source连接器">8.2.5. 文件系统source连接器</h4>
<div class="paragraph">
<p>Apache Flink针对文件系统实现了一个可重置的source连接器，将文件看作流来读取数据。如下面的例子所示：</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="pygments highlight"><code data-lang="scala"><span></span><span class="tok-k">val</span> <span class="tok-n">lineReader</span> <span class="tok-k">=</span> <span class="tok-k">new</span> <span class="tok-nc">TextInputFormat</span><span class="tok-o">(</span><span class="tok-kc">null</span><span class="tok-o">)</span>

<span class="tok-k">val</span> <span class="tok-n">lineStream</span><span class="tok-k">:</span> <span class="tok-kt">DataStream</span><span class="tok-o">[</span><span class="tok-kt">String</span><span class="tok-o">]</span> <span class="tok-k">=</span> <span class="tok-n">env</span><span class="tok-o">.</span><span class="tok-n">readFile</span><span class="tok-o">[</span><span class="tok-kt">String</span><span class="tok-o">](</span>
  <span class="tok-n">lineReader</span><span class="tok-o">,</span>                 <span class="tok-c1">// The FileInputFormat</span>
  <span class="tok-s">&quot;hdfs:///path/to/my/data&quot;</span><span class="tok-o">,</span>  <span class="tok-c1">// The path to read</span>
  <span class="tok-nc">FileProcessingMode</span>
    <span class="tok-o">.</span><span class="tok-nc">PROCESS_CONTINUOUSLY</span><span class="tok-o">,</span>    <span class="tok-c1">// The processing mode</span>
  <span class="tok-mi">30000L</span><span class="tok-o">)</span>                     <span class="tok-c1">// The monitoring interval in ms</span></code></pre>
</div>
</div>
<div class="paragraph">
<p>StreamExecutionEnvironment.readFile()接收如下参数：</p>
</div>
<div class="ulist">
<ul>
<li>
<p>FileInputFormat参数，负责读取文件中的内容。</p>
</li>
<li>
<p>文件路径。如果文件路径指向单个文件，那么将会读取这个文件。如果路径指向一个文件夹，FileInputFormat将会扫描文件夹中所有的文件。</p>
</li>
<li>
<p>PROCESS_CONTINUOUSLY将会周期性的扫描文件，以便扫描到文件新的改变。</p>
</li>
<li>
<p>30000L表示多久扫描一次监听的文件。</p>
</li>
</ul>
</div>
<div class="paragraph">
<p>FileInputFormat是一个特定的InputFormat，用来从文件系统中读取文件。FileInputFormat分两步读取文件。首先扫描文件系统的路径，然后为所有匹配到的文件创建所谓的input splits。一个input split将会定义文件上的一个范围，一般通过读取的开始偏移量和读取长度来定义。在将一个大的文件分割成一堆小的splits以后，这些splits可以分发到不同的读任务，这样就可以并行的读取文件了。FileInputFormat的第二步会接收一个input split，读取被split定义的文件范围，然后返回对应的数据。</p>
</div>
<div class="paragraph">
<p>DataStream应用中使用的FileInputFormat需要实现CheckpointableInputFormat接口。这个接口定义了方法来做检查点和重置文件片段的当前的读取位置。</p>
</div>
<div class="paragraph">
<p>在Flink 1.7中，Flink提供了一些类，这些类继承了FileInputFormat，并实现了CheckpointableInputFormat接口。TextInputFormat一行一行的读取文件，而CsvInputFormat使用逗号分隔符来读取文件。</p>
</div>
</div>
<div class="sect3">
<h4 id="_文件系统sink连接器">8.2.6. 文件系统sink连接器</h4>
<div class="paragraph">
<p>在将流处理应用配置成exactly-once检查点机制，以及配置成所有源数据都能在故障的情况下可以重置，Flink的StreamingFileSink提供了端到端的恰好处理一次语义保证。下面的例子展示了StreamingFileSink的使用方式。</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="pygments highlight"><code data-lang="scala"><span></span><span class="tok-k">val</span> <span class="tok-n">input</span><span class="tok-k">:</span> <span class="tok-kt">DataStream</span><span class="tok-o">[</span><span class="tok-kt">String</span><span class="tok-o">]</span> <span class="tok-k">=</span> <span class="tok-err">…</span>
<span class="tok-k">val</span> <span class="tok-n">sink</span><span class="tok-k">:</span> <span class="tok-kt">StreamingFileSink</span><span class="tok-o">[</span><span class="tok-kt">String</span><span class="tok-o">]</span> <span class="tok-k">=</span> <span class="tok-nc">StreamingFileSink</span>
  <span class="tok-o">.</span><span class="tok-n">forRowFormat</span><span class="tok-o">(</span>
    <span class="tok-k">new</span> <span class="tok-nc">Path</span><span class="tok-o">(</span><span class="tok-s">&quot;/base/path&quot;</span><span class="tok-o">),</span>
    <span class="tok-k">new</span> <span class="tok-nc">SimpleStringEncoder</span><span class="tok-o">[</span><span class="tok-kt">String</span><span class="tok-o">](</span><span class="tok-s">&quot;UTF-8&quot;</span><span class="tok-o">))</span>
  <span class="tok-o">.</span><span class="tok-n">build</span><span class="tok-o">()</span>

<span class="tok-n">input</span><span class="tok-o">.</span><span class="tok-n">addSink</span><span class="tok-o">(</span><span class="tok-n">sink</span><span class="tok-o">)</span></code></pre>
</div>
</div>
<div class="paragraph">
<p>当StreamingFileSink接到一条数据，这条数据将被分配到一个桶（bucket）中。一个桶是我们配置的“/base/path”的子目录。</p>
</div>
<div class="paragraph">
<p>Flink使用BucketAssigner来分配桶。BucketAssigner是一个公共的接口，为每一条数据返回一个BucketId，BucketId决定了数据被分配到哪个子目录。如果没有指定BucketAssigner，Flink将使用DateTimeBucketAssigner来将每条数据分配到每个一个小时所产生的桶中去，基于数据写入的处理时间（机器时间，墙上时钟）。</p>
</div>
<div class="paragraph">
<p>StreamingFileSink提供了exactly-once输出的保证。sink通过一个commit协议来达到恰好处理一次语义的保证。这个commit协议会将文件移动到不同的阶段，有以下状态：in progress，pending，finished。这个协议基于Flink的检查点机制。当Flink决定roll a file时，这个文件将被关闭并移动到pending状态，通过重命名文件来实现。当下一个检查点完成时，pending文件将被移动到finished状态，同样是通过重命名来实现。</p>
</div>
<div class="paragraph">
<p>一旦任务故障，sink任务需要将处于in progress状态的文件重置到上一次检查点的写偏移量。这个可以通过关闭当前in progress的文件，并将文件结尾无效的部分丢弃掉来实现。</p>
</div>
</div>
</div>
<div class="sect2">
<h3 id="_实现自定义源函数">8.3. 实现自定义源函数</h3>
<div class="paragraph">
<p>DataStream API提供了两个接口来实现source连接器：</p>
</div>
<div class="ulist">
<ul>
<li>
<p>SourceFunction和RichSourceFunction可以用来定义非并行的source连接器，source跑在单任务上。</p>
</li>
<li>
<p>ParallelSourceFunction和RichParallelSourceFunction可以用来定义跑在并行实例上的source连接器。</p>
</li>
</ul>
</div>
<div class="paragraph">
<p>除了并行于非并行的区别，这两种接口完全一样。就像process function的rich版本一样，RichSourceFunction和RichParallelSourceFunction的子类可以override open()和close()方法，也可以访问RuntimeContext，RuntimeContext提供了并行任务实例的数量，当前任务实例的索引，以及一些其他信息。</p>
</div>
<div class="paragraph">
<p>SourceFunction和ParallelSourceFunction定义了两种方法：</p>
</div>
<div class="ulist">
<ul>
<li>
<p>void run(SourceContext&lt;T&gt; ctx)</p>
</li>
<li>
<p>cancel()</p>
</li>
</ul>
</div>
<div class="paragraph">
<p>run()方法用来读取或者接收数据然后将数据摄入到Flink应用中。根据接收数据的系统，数据可能是推送的也可能是拉取的。Flink仅仅在特定的线程调用run()方法一次，通常情况下会是一个无限循环来读取或者接收数据并发送数据。任务可以在某个时间点被显式的取消，或者由于流是有限流，当数据被消费完毕时，任务也会停止。</p>
</div>
<div class="paragraph">
<p>当应用被取消或者关闭时，cancel()方法会被Flink调用。为了优雅的关闭Flink应用，run()方法需要在cancel()被调用以后，立即终止执行。下面的例子显示了一个简单的源函数的例子：从0数到Long.MaxValue。</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="pygments highlight"><code data-lang="scala"><span></span><span class="tok-k">class</span> <span class="tok-nc">CountSource</span> <span class="tok-k">extends</span> <span class="tok-nc">SourceFunction</span><span class="tok-o">[</span><span class="tok-kt">Long</span><span class="tok-o">]</span> <span class="tok-o">{</span>
  <span class="tok-k">var</span> <span class="tok-n">isRunning</span><span class="tok-k">:</span> <span class="tok-kt">Boolean</span> <span class="tok-o">=</span> <span class="tok-kc">true</span>

  <span class="tok-k">override</span> <span class="tok-k">def</span> <span class="tok-n">run</span><span class="tok-o">(</span><span class="tok-n">ctx</span><span class="tok-k">:</span> <span class="tok-kt">SourceFunction.SourceContext</span><span class="tok-o">[</span><span class="tok-kt">Long</span><span class="tok-o">])</span> <span class="tok-k">=</span> <span class="tok-o">{</span>

    <span class="tok-k">var</span> <span class="tok-n">cnt</span><span class="tok-k">:</span> <span class="tok-kt">Long</span> <span class="tok-o">=</span> <span class="tok-o">-</span><span class="tok-mi">1</span>
    <span class="tok-k">while</span> <span class="tok-o">(</span><span class="tok-n">isRunning</span> <span class="tok-o">&amp;&amp;</span> <span class="tok-n">cnt</span> <span class="tok-o">&lt;</span> <span class="tok-nc">Long</span><span class="tok-o">.</span><span class="tok-nc">MaxValue</span><span class="tok-o">)</span> <span class="tok-o">{</span>
      <span class="tok-n">cnt</span> <span class="tok-o">+=</span> <span class="tok-mi">1</span>
      <span class="tok-n">ctx</span><span class="tok-o">.</span><span class="tok-n">collect</span><span class="tok-o">(</span><span class="tok-n">cnt</span><span class="tok-o">)</span>
    <span class="tok-o">}</span>
  <span class="tok-o">}</span>

  <span class="tok-k">override</span> <span class="tok-k">def</span> <span class="tok-n">cancel</span><span class="tok-o">()</span> <span class="tok-k">=</span> <span class="tok-n">isRunning</span> <span class="tok-k">=</span> <span class="tok-kc">false</span>
<span class="tok-o">}</span></code></pre>
</div>
</div>
<div class="sect3">
<h4 id="_可重置的源函数">8.3.1. 可重置的源函数</h4>
<div class="paragraph">
<p>之前我们讲过，应用程序只有使用可以重播输出数据的数据源时，才能提供令人满意的一致性保证。如果外部系统暴露了获取和重置读偏移量的API，那么source函数就可以重播源数据。这样的例子包括一些能够提供文件流的偏移量的文件系统，或者提供seek方法用来移动到文件的特定位置的文件系统。或者Apache Kafka这种可以为每一个主题的分区提供偏移量并且可以设置分区的读位置的系统。一个反例就是source连接器连接的是socket，socket将会立即丢弃已经发送过的数据。</p>
</div>
<div class="paragraph">
<p>支持重播输出的源函数需要和Flink的检查点机制集成起来，还需要在检查点被处理时，持久化当前所有的读取位置。当应用从一个保存点（savepoint）恢复或者从故障恢复时，Flink会从最近一次的检查点或者保存点中获取读偏移量。如果程序开始时并不存在状态，那么读偏移量将会被设置到一个默认值。一个可重置的源函数需要实现CheckpointedFunction接口，还需要能够存储读偏移量和相关的元数据，例如文件的路径，分区的ID。这些数据将被保存在list state或者union list state中。</p>
</div>
<div class="paragraph">
<p>下面的例子将CountSource重写为可重置的数据源。</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="pygments highlight"><code data-lang="scala"><span></span><span class="tok-k">class</span> <span class="tok-nc">ResettableCountSource</span>
    <span class="tok-k">extends</span> <span class="tok-nc">SourceFunction</span><span class="tok-o">[</span><span class="tok-kt">Long</span><span class="tok-o">]</span> <span class="tok-k">with</span> <span class="tok-nc">CheckpointedFunction</span> <span class="tok-o">{</span>

  <span class="tok-k">var</span> <span class="tok-n">isRunning</span><span class="tok-k">:</span> <span class="tok-kt">Boolean</span> <span class="tok-o">=</span> <span class="tok-kc">true</span>
  <span class="tok-k">var</span> <span class="tok-n">cnt</span><span class="tok-k">:</span> <span class="tok-kt">Long</span> <span class="tok-o">=</span> <span class="tok-k">_</span>
  <span class="tok-k">var</span> <span class="tok-n">offsetState</span><span class="tok-k">:</span> <span class="tok-kt">ListState</span><span class="tok-o">[</span><span class="tok-kt">Long</span><span class="tok-o">]</span> <span class="tok-k">=</span> <span class="tok-k">_</span>

  <span class="tok-k">override</span> <span class="tok-k">def</span> <span class="tok-n">run</span><span class="tok-o">(</span><span class="tok-n">ctx</span><span class="tok-k">:</span> <span class="tok-kt">SourceFunction.SourceContext</span><span class="tok-o">[</span><span class="tok-kt">Long</span><span class="tok-o">])</span> <span class="tok-k">=</span> <span class="tok-o">{</span>
    <span class="tok-k">while</span> <span class="tok-o">(</span><span class="tok-n">isRunning</span> <span class="tok-o">&amp;&amp;</span> <span class="tok-n">cnt</span> <span class="tok-o">&lt;</span> <span class="tok-nc">Long</span><span class="tok-o">.</span><span class="tok-nc">MaxValue</span><span class="tok-o">)</span> <span class="tok-o">{</span>
      <span class="tok-c1">// synchronize data emission and checkpoints</span>
      <span class="tok-n">ctx</span><span class="tok-o">.</span><span class="tok-n">getCheckpointLock</span><span class="tok-o">.</span><span class="tok-n">synchronized</span> <span class="tok-o">{</span>
        <span class="tok-n">cnt</span> <span class="tok-o">+=</span> <span class="tok-mi">1</span>
        <span class="tok-n">ctx</span><span class="tok-o">.</span><span class="tok-n">collect</span><span class="tok-o">(</span><span class="tok-n">cnt</span><span class="tok-o">)</span>
      <span class="tok-o">}</span>
    <span class="tok-o">}</span>
  <span class="tok-o">}</span>

  <span class="tok-k">override</span> <span class="tok-k">def</span> <span class="tok-n">cancel</span><span class="tok-o">()</span> <span class="tok-k">=</span> <span class="tok-n">isRunning</span> <span class="tok-k">=</span> <span class="tok-kc">false</span>

  <span class="tok-k">override</span> <span class="tok-k">def</span> <span class="tok-n">snapshotState</span><span class="tok-o">(</span><span class="tok-n">snapshotCtx</span><span class="tok-k">:</span> <span class="tok-kt">FunctionSnapshotContext</span><span class="tok-o">)</span><span class="tok-k">:</span> <span class="tok-kt">Unit</span> <span class="tok-o">=</span> <span class="tok-o">{</span>
    <span class="tok-c1">// remove previous cnt</span>
    <span class="tok-n">offsetState</span><span class="tok-o">.</span><span class="tok-n">clear</span><span class="tok-o">()</span>
    <span class="tok-c1">// add current cnt</span>
    <span class="tok-n">offsetState</span><span class="tok-o">.</span><span class="tok-n">add</span><span class="tok-o">(</span><span class="tok-n">cnt</span><span class="tok-o">)</span>
  <span class="tok-o">}</span>

  <span class="tok-k">override</span> <span class="tok-k">def</span> <span class="tok-n">initializeState</span><span class="tok-o">(</span>
      <span class="tok-n">initCtx</span><span class="tok-k">:</span> <span class="tok-kt">FunctionInitializationContext</span><span class="tok-o">)</span><span class="tok-k">:</span> <span class="tok-kt">Unit</span> <span class="tok-o">=</span> <span class="tok-o">{</span>

    <span class="tok-k">val</span> <span class="tok-n">desc</span> <span class="tok-k">=</span> <span class="tok-k">new</span> <span class="tok-nc">ListStateDescriptor</span><span class="tok-o">[</span><span class="tok-kt">Long</span><span class="tok-o">](</span><span class="tok-s">&quot;offset&quot;</span><span class="tok-o">,</span> <span class="tok-n">classOf</span><span class="tok-o">[</span><span class="tok-kt">Long</span><span class="tok-o">])</span>
    <span class="tok-n">offsetState</span> <span class="tok-k">=</span> <span class="tok-n">initCtx</span><span class="tok-o">.</span><span class="tok-n">getOperatorStateStore</span><span class="tok-o">.</span><span class="tok-n">getListState</span><span class="tok-o">(</span><span class="tok-n">desc</span><span class="tok-o">)</span>
    <span class="tok-c1">// initialize cnt variable</span>
    <span class="tok-k">val</span> <span class="tok-n">it</span> <span class="tok-k">=</span> <span class="tok-n">offsetState</span><span class="tok-o">.</span><span class="tok-n">get</span><span class="tok-o">()</span>
    <span class="tok-n">cnt</span> <span class="tok-k">=</span> <span class="tok-k">if</span> <span class="tok-o">(</span><span class="tok-kc">null</span> <span class="tok-o">==</span> <span class="tok-n">it</span> <span class="tok-o">||</span> <span class="tok-o">!</span><span class="tok-n">it</span><span class="tok-o">.</span><span class="tok-n">iterator</span><span class="tok-o">().</span><span class="tok-n">hasNext</span><span class="tok-o">)</span> <span class="tok-o">{</span>
      <span class="tok-o">-</span><span class="tok-mi">1L</span>
    <span class="tok-o">}</span> <span class="tok-k">else</span> <span class="tok-o">{</span>
      <span class="tok-n">it</span><span class="tok-o">.</span><span class="tok-n">iterator</span><span class="tok-o">().</span><span class="tok-n">next</span><span class="tok-o">()</span>
    <span class="tok-o">}</span>
  <span class="tok-o">}</span>
<span class="tok-o">}</span></code></pre>
</div>
</div>
</div>
</div>
<div class="sect2">
<h3 id="_实现自定义sink函数">8.4. 实现自定义sink函数</h3>
<div class="paragraph">
<p>DataStream API中，任何运算符或者函数都可以向外部系统发送数据。DataStream不需要最终流向sink运算符。例如，我们可能实现了一个FlatMapFunction，这个函数将每一个接收到的数据通过HTTP POST请求发送出去，而不使用Collector发送到下一个运算符。DataStream API也提供了SinkFunction接口以及对应的rich版本RichSinkFunction抽象类。SinkFunction接口提供了一个方法：</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="pygments highlight"><code data-lang="scala"><span></span><span class="tok-n">void</span> <span class="tok-n">invode</span><span class="tok-o">(</span><span class="tok-nc">IN</span> <span class="tok-n">value</span><span class="tok-o">,</span> <span class="tok-nc">Context</span> <span class="tok-n">ctx</span><span class="tok-o">)</span></code></pre>
</div>
</div>
<div class="paragraph">
<p>SinkFunction的Context可以访问当前处理时间，当前水位线，以及数据的时间戳。</p>
</div>
<div class="paragraph">
<p>下面的例子展示了一个简单的SinkFunction，可以将传感器读数写入到socket中去。需要注意的是，我们需要在启动Flink程序前启动一个监听相关端口的进程。否则将会抛出ConnectException异常。可以运行“nc -l localhost 9191”命令。</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="pygments highlight"><code data-lang="scala"><span></span><span class="tok-k">val</span> <span class="tok-n">readings</span><span class="tok-k">:</span> <span class="tok-kt">DataStream</span><span class="tok-o">[</span><span class="tok-kt">SensorReading</span><span class="tok-o">]</span> <span class="tok-k">=</span> <span class="tok-o">...</span>

<span class="tok-c1">// write the sensor readings to a socket</span>
<span class="tok-n">readings</span><span class="tok-o">.</span><span class="tok-n">addSink</span><span class="tok-o">(</span><span class="tok-k">new</span> <span class="tok-nc">SimpleSocketSink</span><span class="tok-o">(</span><span class="tok-s">&quot;localhost&quot;</span><span class="tok-o">,</span> <span class="tok-mi">9191</span><span class="tok-o">))</span>
  <span class="tok-c1">// set parallelism to 1 because only one thread can write to a socket</span>
  <span class="tok-o">.</span><span class="tok-n">setParallelism</span><span class="tok-o">(</span><span class="tok-mi">1</span><span class="tok-o">)</span>

<span class="tok-c1">// -----</span>

<span class="tok-k">class</span> <span class="tok-nc">SimpleSocketSink</span><span class="tok-o">(</span><span class="tok-k">val</span> <span class="tok-n">host</span><span class="tok-k">:</span> <span class="tok-kt">String</span><span class="tok-o">,</span> <span class="tok-k">val</span> <span class="tok-n">port</span><span class="tok-k">:</span> <span class="tok-kt">Int</span><span class="tok-o">)</span>
    <span class="tok-k">extends</span> <span class="tok-nc">RichSinkFunction</span><span class="tok-o">[</span><span class="tok-kt">SensorReading</span><span class="tok-o">]</span> <span class="tok-o">{</span>

  <span class="tok-k">var</span> <span class="tok-n">socket</span><span class="tok-k">:</span> <span class="tok-kt">Socket</span> <span class="tok-o">=</span> <span class="tok-k">_</span>
  <span class="tok-k">var</span> <span class="tok-n">writer</span><span class="tok-k">:</span> <span class="tok-kt">PrintStream</span> <span class="tok-o">=</span> <span class="tok-k">_</span>

  <span class="tok-k">override</span> <span class="tok-k">def</span> <span class="tok-n">open</span><span class="tok-o">(</span><span class="tok-n">config</span><span class="tok-k">:</span> <span class="tok-kt">Configuration</span><span class="tok-o">)</span><span class="tok-k">:</span> <span class="tok-kt">Unit</span> <span class="tok-o">=</span> <span class="tok-o">{</span>
    <span class="tok-c1">// open socket and writer</span>
    <span class="tok-n">socket</span> <span class="tok-k">=</span> <span class="tok-k">new</span> <span class="tok-nc">Socket</span><span class="tok-o">(</span><span class="tok-nc">InetAddress</span><span class="tok-o">.</span><span class="tok-n">getByName</span><span class="tok-o">(</span><span class="tok-n">host</span><span class="tok-o">),</span> <span class="tok-n">port</span><span class="tok-o">)</span>
    <span class="tok-n">writer</span> <span class="tok-k">=</span> <span class="tok-k">new</span> <span class="tok-nc">PrintStream</span><span class="tok-o">(</span><span class="tok-n">socket</span><span class="tok-o">.</span><span class="tok-n">getOutputStream</span><span class="tok-o">)</span>
  <span class="tok-o">}</span>

  <span class="tok-k">override</span> <span class="tok-k">def</span> <span class="tok-n">invoke</span><span class="tok-o">(</span>
      <span class="tok-n">value</span><span class="tok-k">:</span> <span class="tok-kt">SensorReading</span><span class="tok-o">,</span>
      <span class="tok-n">ctx</span><span class="tok-k">:</span> <span class="tok-kt">SinkFunction.Context</span><span class="tok-o">[</span><span class="tok-k">_</span><span class="tok-o">])</span><span class="tok-k">:</span> <span class="tok-kt">Unit</span> <span class="tok-o">=</span> <span class="tok-o">{</span>
    <span class="tok-c1">// write sensor reading to socket</span>
    <span class="tok-n">writer</span><span class="tok-o">.</span><span class="tok-n">println</span><span class="tok-o">(</span><span class="tok-n">value</span><span class="tok-o">.</span><span class="tok-n">toString</span><span class="tok-o">)</span>
    <span class="tok-n">writer</span><span class="tok-o">.</span><span class="tok-n">flush</span><span class="tok-o">()</span>
  <span class="tok-o">}</span>

  <span class="tok-k">override</span> <span class="tok-k">def</span> <span class="tok-n">close</span><span class="tok-o">()</span><span class="tok-k">:</span> <span class="tok-kt">Unit</span> <span class="tok-o">=</span> <span class="tok-o">{</span>
    <span class="tok-c1">// close writer and socket</span>
    <span class="tok-n">writer</span><span class="tok-o">.</span><span class="tok-n">close</span><span class="tok-o">()</span>
    <span class="tok-n">socket</span><span class="tok-o">.</span><span class="tok-n">close</span><span class="tok-o">()</span>
  <span class="tok-o">}</span>
<span class="tok-o">}</span></code></pre>
</div>
</div>
<div class="paragraph">
<p>之前我们讨论过，端到端的一致性保证建立在sink连接器的属性上面。为了达到端到端的恰好处理一次语义的目的，应用程序需要幂等性的sink连接器或者事务性的sink连接器。上面例子中的SinkFunction既不是幂等写入也不是事务性的写入。由于socket具有只能添加（append-only）这样的属性，所以不可能实现幂等性的写入。又因为socket不具备内置的事务支持，所以事务性写入就只能使用Flink的WAL sink特性来实现了。接下来我们将学习如何实现幂等sink连接器和事务sink连接器。</p>
</div>
<div class="sect3">
<h4 id="_幂等sink连接器">8.4.1. 幂等sink连接器</h4>
<div class="paragraph">
<p>对于大多数应用，SinkFunction接口足以实现一个幂等性写入的sink连接器了。需要以下两个条件：</p>
</div>
<div class="ulist">
<ul>
<li>
<p>结果数据必须具有确定性的key，在这个key上面幂等性更新才能实现。例如一个计算每分钟每个传感器的平均温度值的程序，确定性的key值可以是传感器的ID和每分钟的时间戳。确定性的key值，对于在故障恢复的场景下，能够正确的覆盖结果非常的重要。</p>
</li>
<li>
<p>外部系统支持针对每个key的更新，例如关系型数据库或者key-value存储。</p>
</li>
</ul>
</div>
<div class="paragraph">
<p>下面的例子展示了如何实现一个针对JDBC数据库的幂等写入sink连接器，这里使用的是Apache Derby数据库。</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="pygments highlight"><code data-lang="scala"><span></span><span class="tok-k">val</span> <span class="tok-n">readings</span><span class="tok-k">:</span> <span class="tok-kt">DataStream</span><span class="tok-o">[</span><span class="tok-kt">SensorReading</span><span class="tok-o">]</span> <span class="tok-k">=</span> <span class="tok-o">???</span>

<span class="tok-c1">// write the sensor readings to a Derby table</span>
<span class="tok-n">readings</span><span class="tok-o">.</span><span class="tok-n">addSink</span><span class="tok-o">(</span><span class="tok-k">new</span> <span class="tok-nc">DerbyUpsertSink</span><span class="tok-o">)</span>

<span class="tok-c1">// -----</span>

<span class="tok-k">class</span> <span class="tok-nc">DerbyUpsertSink</span> <span class="tok-k">extends</span> <span class="tok-nc">RichSinkFunction</span><span class="tok-o">[</span><span class="tok-kt">SensorReading</span><span class="tok-o">]</span> <span class="tok-o">{</span>
  <span class="tok-k">var</span> <span class="tok-n">conn</span><span class="tok-k">:</span> <span class="tok-kt">Connection</span> <span class="tok-o">=</span> <span class="tok-k">_</span>
  <span class="tok-k">var</span> <span class="tok-n">insertStmt</span><span class="tok-k">:</span> <span class="tok-kt">PreparedStatement</span> <span class="tok-o">=</span> <span class="tok-k">_</span>
  <span class="tok-k">var</span> <span class="tok-n">updateStmt</span><span class="tok-k">:</span> <span class="tok-kt">PreparedStatement</span> <span class="tok-o">=</span> <span class="tok-k">_</span>

  <span class="tok-k">override</span> <span class="tok-k">def</span> <span class="tok-n">open</span><span class="tok-o">(</span><span class="tok-n">parameters</span><span class="tok-k">:</span> <span class="tok-kt">Configuration</span><span class="tok-o">)</span><span class="tok-k">:</span> <span class="tok-kt">Unit</span> <span class="tok-o">=</span> <span class="tok-o">{</span>
    <span class="tok-c1">// connect to embedded in-memory Derby</span>
    <span class="tok-n">conn</span> <span class="tok-k">=</span> <span class="tok-nc">DriverManager</span><span class="tok-o">.</span><span class="tok-n">getConnection</span><span class="tok-o">(</span>
       <span class="tok-s">&quot;jdbc:derby:memory:flinkExample&quot;</span><span class="tok-o">,</span>
       <span class="tok-k">new</span> <span class="tok-nc">Properties</span><span class="tok-o">())</span>
    <span class="tok-c1">// prepare insert and update statements</span>
    <span class="tok-n">insertStmt</span> <span class="tok-k">=</span> <span class="tok-n">conn</span><span class="tok-o">.</span><span class="tok-n">prepareStatement</span><span class="tok-o">(</span>
      <span class="tok-s">&quot;INSERT INTO Temperatures (sensor, temp) VALUES (?, ?)&quot;</span><span class="tok-o">)</span>
    <span class="tok-n">updateStmt</span> <span class="tok-k">=</span> <span class="tok-n">conn</span><span class="tok-o">.</span><span class="tok-n">prepareStatement</span><span class="tok-o">(</span>
      <span class="tok-s">&quot;UPDATE Temperatures SET temp = ? WHERE sensor = ?&quot;</span><span class="tok-o">)</span>
  <span class="tok-o">}</span>

  <span class="tok-k">override</span> <span class="tok-k">def</span> <span class="tok-n">invoke</span><span class="tok-o">(</span><span class="tok-n">r</span><span class="tok-k">:</span> <span class="tok-kt">SensorReading</span><span class="tok-o">,</span> <span class="tok-n">context</span><span class="tok-k">:</span> <span class="tok-kt">Context</span><span class="tok-o">[</span><span class="tok-k">_</span><span class="tok-o">])</span><span class="tok-k">:</span> <span class="tok-kt">Unit</span> <span class="tok-o">=</span> <span class="tok-o">{</span>
    <span class="tok-c1">// set parameters for update statement and execute it</span>
    <span class="tok-n">updateStmt</span><span class="tok-o">.</span><span class="tok-n">setDouble</span><span class="tok-o">(</span><span class="tok-mi">1</span><span class="tok-o">,</span> <span class="tok-n">r</span><span class="tok-o">.</span><span class="tok-n">temperature</span><span class="tok-o">)</span>
    <span class="tok-n">updateStmt</span><span class="tok-o">.</span><span class="tok-n">setString</span><span class="tok-o">(</span><span class="tok-mi">2</span><span class="tok-o">,</span> <span class="tok-n">r</span><span class="tok-o">.</span><span class="tok-n">id</span><span class="tok-o">)</span>
    <span class="tok-n">updateStmt</span><span class="tok-o">.</span><span class="tok-n">execute</span><span class="tok-o">()</span>
    <span class="tok-c1">// execute insert statement if update statement did not update any row</span>
    <span class="tok-k">if</span> <span class="tok-o">(</span><span class="tok-n">updateStmt</span><span class="tok-o">.</span><span class="tok-n">getUpdateCount</span> <span class="tok-o">==</span> <span class="tok-mi">0</span><span class="tok-o">)</span> <span class="tok-o">{</span>
      <span class="tok-c1">// set parameters for insert statement</span>
      <span class="tok-n">insertStmt</span><span class="tok-o">.</span><span class="tok-n">setString</span><span class="tok-o">(</span><span class="tok-mi">1</span><span class="tok-o">,</span> <span class="tok-n">r</span><span class="tok-o">.</span><span class="tok-n">id</span><span class="tok-o">)</span>
      <span class="tok-n">insertStmt</span><span class="tok-o">.</span><span class="tok-n">setDouble</span><span class="tok-o">(</span><span class="tok-mi">2</span><span class="tok-o">,</span> <span class="tok-n">r</span><span class="tok-o">.</span><span class="tok-n">temperature</span><span class="tok-o">)</span>
      <span class="tok-c1">// execute insert statement</span>
      <span class="tok-n">insertStmt</span><span class="tok-o">.</span><span class="tok-n">execute</span><span class="tok-o">()</span>
    <span class="tok-o">}</span>
  <span class="tok-o">}</span>

  <span class="tok-k">override</span> <span class="tok-k">def</span> <span class="tok-n">close</span><span class="tok-o">()</span><span class="tok-k">:</span> <span class="tok-kt">Unit</span> <span class="tok-o">=</span> <span class="tok-o">{</span>
    <span class="tok-n">insertStmt</span><span class="tok-o">.</span><span class="tok-n">close</span><span class="tok-o">()</span>
    <span class="tok-n">updateStmt</span><span class="tok-o">.</span><span class="tok-n">close</span><span class="tok-o">()</span>
    <span class="tok-n">conn</span><span class="tok-o">.</span><span class="tok-n">close</span><span class="tok-o">()</span>
  <span class="tok-o">}</span>
<span class="tok-o">}</span></code></pre>
</div>
</div>
<div class="paragraph">
<p>由于Apache Derby并没有提供内置的UPSERT方法，所以这个sink连接器实现了UPSERT写。具体实现方法是首先去尝试更新一行数据，如果这行数据不存在，则插入新的一行数据。</p>
</div>
</div>
<div class="sect3">
<h4 id="_事务性sink连接器">8.4.2. 事务性sink连接器</h4>
<div class="paragraph">
<p>事务写入sink连接器需要和Flink的检查点机制集成，因为只有在检查点成功完成以后，事务写入sink连接器才会向外部系统commit数据。</p>
</div>
<div class="paragraph">
<p>为了简化事务性sink的实现，Flink提供了两个模版用来实现自定义sink运算符。这两个模版都实现了CheckpointListener接口。CheckpointListener接口将会从JobManager接收到检查点完成的通知。</p>
</div>
<div class="ulist">
<ul>
<li>
<p>GenericWriteAheadSink模版会收集检查点之前的所有的数据，并将数据存储到sink任务的运算符状态中。状态保存到了检查点中，并在任务故障的情况下恢复。当任务接收到检查点完成的通知时，任务会将所有的数据写入到外部系统中。</p>
</li>
<li>
<p>TwoPhaseCommitSinkFunction模版利用了外部系统的事务特性。对于每一个检查点，任务首先开始一个新的事务，并将接下来所有的数据都写到外部系统的当前事务上下文中去。当任务接收到检查点完成的通知时，sink连接器将会commit这个事务。</p>
</li>
</ul>
</div>
<div class="paragraph">
<p><strong>GENERICWRITEAHEADSINK</strong></p>
</div>
<div class="paragraph">
<p>GenericWriteAheadSink使得sink运算符可以很方便的实现。这个运算符和Flink的检查点机制集成使用，目标是将每一条数据恰好一次写入到外部系统中去。需要注意的是，在发生故障的情况下，write-ahead log sink可能会不止一次的发送相同的数据。所以GenericWriteAheadSink无法提供完美无缺的恰好处理一次语义的一致性保证，而是仅能提供at-least-once这样的保证。我们接下来详细的讨论这些场景。</p>
</div>
<div class="paragraph">
<p>GenericWriteAheadSink的原理是将接收到的所有数据都追加到有检查点分割好的预写式日志中去。每当sink运算符碰到检查点屏障，运算符将会开辟一个新的section，并将接下来的所有数据都追加到新的section中去。WAL（预写式日志）将会保存到运算符状态中。由于log能被恢复，所有不会有数据丢失。</p>
</div>
<div class="paragraph">
<p>当GenericWriteAheadSink接收到检查点完成的通知时，将会发送对应检查点的WAL中存储的所有数据。当所有数据发送成功，对应的检查点必须在内部提交。</p>
</div>
<div class="paragraph">
<p>检查点的提交分两步。第一步，sink持久化检查点被提交的信息。第二步，删除WAL中所有的数据。我们不能将commit信息保存在Flink应用程序状态中，因为状态不是持久化的，会在故障恢复时重置状态。相反，GenericWriteAheadSink依赖于可插拔的组件在一个外部持久化存储中存储和查找提交信息。这个组件就是CheckpointCommitter。</p>
</div>
<div class="paragraph">
<p>继承GenericWriteAheadSink的运算符需要提供三个构造器函数。</p>
</div>
<div class="ulist">
<ul>
<li>
<p>CheckpointCommitter</p>
</li>
<li>
<p>TypeSerializer，用来序列化输入数据。</p>
</li>
<li>
<p>一个job ID，传给CheckpointCommitter，当应用重启时可以识别commit信息。</p>
</li>
</ul>
</div>
<div class="paragraph">
<p>还有，write-ahead运算符需要实现一个单独的方法：</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="pygments highlight"><code data-lang="java"><span></span><span class="tok-kt">boolean</span> <span class="tok-nf">sendValues</span><span class="tok-o">(</span><span class="tok-n">Iterable</span><span class="tok-o">&lt;</span><span class="tok-n">IN</span><span class="tok-o">&gt;</span> <span class="tok-n">values</span><span class="tok-o">,</span> <span class="tok-kt">long</span> <span class="tok-n">chkpntId</span><span class="tok-o">,</span> <span class="tok-kt">long</span> <span class="tok-n">timestamp</span><span class="tok-o">)</span></code></pre>
</div>
</div>
<div class="paragraph">
<p>当检查点完成时，GenericWriteAheadSink调用sendValues()方法来将数据写入到外部存储系统中。这个方法接收一个检查点对应的所有数据的迭代器，检查点的ID，检查点被处理时的时间戳。当数据写入成功时，方法必须返回true，写入失败返回false。</p>
</div>
<div class="paragraph">
<p>下面的例子展示了如何实现一个写入到标准输出的write-ahead sink。它使用了FileCheckpointCommitter。</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="pygments highlight"><code data-lang="scala"><span></span><span class="tok-k">val</span> <span class="tok-n">readings</span><span class="tok-k">:</span> <span class="tok-kt">DataStream</span><span class="tok-o">[</span><span class="tok-kt">SensorReading</span><span class="tok-o">]</span> <span class="tok-k">=</span> <span class="tok-o">???</span>

<span class="tok-c1">// write the sensor readings to the standard out via a write-ahead log</span>
<span class="tok-n">readings</span><span class="tok-o">.</span><span class="tok-n">transform</span><span class="tok-o">(</span>
  <span class="tok-s">&quot;WriteAheadSink&quot;</span><span class="tok-o">,</span> <span class="tok-k">new</span> <span class="tok-nc">SocketWriteAheadSink</span><span class="tok-o">)</span>

<span class="tok-c1">// -----</span>

<span class="tok-k">class</span> <span class="tok-nc">StdOutWriteAheadSink</span> <span class="tok-k">extends</span> <span class="tok-nc">GenericWriteAheadSink</span><span class="tok-o">[</span><span class="tok-kt">SensorReading</span><span class="tok-o">](</span>
    <span class="tok-c1">// CheckpointCommitter that commits checkpoints to the local filesystem</span>
    <span class="tok-k">new</span> <span class="tok-nc">FileCheckpointCommitter</span><span class="tok-o">(</span><span class="tok-nc">System</span><span class="tok-o">.</span><span class="tok-n">getProperty</span><span class="tok-o">(</span><span class="tok-s">&quot;java.io.tmpdir&quot;</span><span class="tok-o">)),</span>
    <span class="tok-c1">// Serializer for records</span>
    <span class="tok-n">createTypeInformation</span><span class="tok-o">[</span><span class="tok-kt">SensorReading</span><span class="tok-o">]</span>
      <span class="tok-o">.</span><span class="tok-n">createSerializer</span><span class="tok-o">(</span><span class="tok-k">new</span> <span class="tok-nc">ExecutionConfig</span><span class="tok-o">),</span>
    <span class="tok-c1">// Random JobID used by the CheckpointCommitter</span>
    <span class="tok-nc">UUID</span><span class="tok-o">.</span><span class="tok-n">randomUUID</span><span class="tok-o">.</span><span class="tok-n">toString</span><span class="tok-o">)</span> <span class="tok-o">{</span>

  <span class="tok-k">override</span> <span class="tok-k">def</span> <span class="tok-n">sendValues</span><span class="tok-o">(</span>
      <span class="tok-n">readings</span><span class="tok-k">:</span> <span class="tok-kt">Iterable</span><span class="tok-o">[</span><span class="tok-kt">SensorReading</span><span class="tok-o">],</span>
      <span class="tok-n">checkpointId</span><span class="tok-k">:</span> <span class="tok-kt">Long</span><span class="tok-o">,</span>
      <span class="tok-n">timestamp</span><span class="tok-k">:</span> <span class="tok-kt">Long</span><span class="tok-o">)</span><span class="tok-k">:</span> <span class="tok-kt">Boolean</span> <span class="tok-o">=</span> <span class="tok-o">{</span>

    <span class="tok-k">for</span> <span class="tok-o">(</span><span class="tok-n">r</span> <span class="tok-k">&lt;-</span> <span class="tok-n">readings</span><span class="tok-o">.</span><span class="tok-n">asScala</span><span class="tok-o">)</span> <span class="tok-o">{</span>
      <span class="tok-c1">// write record to standard out</span>
      <span class="tok-n">println</span><span class="tok-o">(</span><span class="tok-n">r</span><span class="tok-o">)</span>
    <span class="tok-o">}</span>
    <span class="tok-kc">true</span>
  <span class="tok-o">}</span>
<span class="tok-o">}</span></code></pre>
</div>
</div>
<div class="paragraph">
<p>之前我们讲过，GenericWriteAheadSink无法提供完美的exactly-once保证。有两个故障状况会导致数据可能被发送不止一次。</p>
</div>
<div class="ulist">
<ul>
<li>
<p>当任务执行sendValues()方法时，程序挂掉了。如果外部系统无法原子性的写入所有数据（要么都写入要么都不写），一些数据可能会写入，而另一些数据并没有被写入。由于checkpoint还没有commit，所以在任务恢复的过程中一些数据可能会被再次写入。</p>
</li>
<li>
<p>所有数据都写入成功了，sendValues()方法也返回true了；但在CheckpointCommitter方法被调用之前程序挂了，或者CheckpointCommitter在commit检查点时失败了。那么在恢复的过程中，所有未被提交的检查点将会被重新写入。</p>
</li>
</ul>
</div>
<div class="paragraph">
<p><strong>TWOPHASECOMMITSINKFUNCTION</strong></p>
</div>
<div class="paragraph">
<p>Flink提供了TwoPhaseCommitSinkFunction接口来简化sink函数的实现。这个接口保证了端到端的exactly-once语义。2PC sink函数是否提供这样的一致性保证取决于我们的实现细节。我们需要讨论一个问题：“2PC协议是否开销太大？”</p>
</div>
<div class="paragraph">
<p>通常来讲，为了保证分布式系统的一致性，2PC是一个非常昂贵的方法。尽管如此，在Flink的语境下，2PC协议针对每一个检查点只运行一次。TwoPhaseCommitSinkFunction和WAL sink很相似，不同点在于前者不会将数据收集到state中，而是会写入到外部系统事务的上下文中。</p>
</div>
<div class="paragraph">
<p>TwoPhaseCommitSinkFunction实现了以下协议。在sink任务发送出第一条数据之前，任务将在外部系统中开始一个事务，所有接下来的数据将被写入这个事务的上下文中。当JobManager初始化检查点并将检查点屏障插入到流中的时候，2PC协议的投票阶段开始。当运算符接收到检查点屏障，运算符将保存它的状态，当保存完成时，运算符将发送一个acknowledgement信息给JobManager。当sink任务接收到检查点屏障时，运算符将会持久化它的状态，并准备提交当前的事务，以及acknowledge JobManager中的检查点。发送给JobManager的acknowledgement信息类似于2PC协议中的commit投票。sink任务还不能提交事务，因为它还没有保证所有的任务都已经完成了它们的检查点操作。sink任务也会为下一个检查点屏障之前的所有数据开始一个新的事务。</p>
</div>
<div class="paragraph">
<p>当JobManager成功接收到所有任务实例发出的检查点操作成功的通知时，JobManager将会把检查点完成的通知发送给所有感兴趣的任务。这里的通知对应于2PC协议的提交命令。当sink任务接收到通知时，它将commit所有处于开启状态的事务。一旦sink任务acknowledge了检查点操作，它必须能够commit对应的事务，即使任务发生故障。如果commit失败，数据将会丢失。</p>
</div>
<div class="paragraph">
<p>让我们总结一下外部系统需要满足什么样的要求：</p>
</div>
<div class="ulist">
<ul>
<li>
<p>外部系统必须提供事务支持，或者sink的实现能在外部系统上模拟事务功能。</p>
</li>
<li>
<p>在检查点操作期间，事务必须处于open状态，并接收这段时间数据的持续写入。</p>
</li>
<li>
<p>事务必须等到检查点操作完成的通知到来才可以提交。在恢复周期中，可能需要一段时间等待。如果sink系统关闭了事务（例如超时了），那么未被commit的数据将会丢失。</p>
</li>
<li>
<p>sink必须在进程挂掉后能够恢复事务。一些sink系统会提供事务ID，用来commit或者abort一个开始的事务。</p>
</li>
<li>
<p>commit一个事务必须是一个幂等性操作。sink系统或者外部系统能够观察到事务已经被提交，或者重复提交并没有副作用。</p>
</li>
</ul>
</div>
<div class="paragraph">
<p>下面的例子可能会让上面的一些概念好理解一些。</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="pygments highlight"><code data-lang="scala"><span></span><span class="tok-k">class</span> <span class="tok-nc">TransactionalFileSink</span><span class="tok-o">(</span><span class="tok-k">val</span> <span class="tok-n">targetPath</span><span class="tok-k">:</span> <span class="tok-kt">String</span><span class="tok-o">,</span> <span class="tok-k">val</span> <span class="tok-n">tempPath</span><span class="tok-k">:</span> <span class="tok-kt">String</span><span class="tok-o">)</span>
    <span class="tok-k">extends</span> <span class="tok-nc">TwoPhaseCommitSinkFunction</span><span class="tok-o">[(</span><span class="tok-kt">String</span>, <span class="tok-kt">Double</span><span class="tok-o">)</span>, <span class="tok-kt">String</span>, <span class="tok-kt">Void</span><span class="tok-o">](</span>
      <span class="tok-n">createTypeInformation</span><span class="tok-o">[</span><span class="tok-kt">String</span><span class="tok-o">].</span><span class="tok-n">createSerializer</span><span class="tok-o">(</span><span class="tok-k">new</span> <span class="tok-nc">ExecutionConfig</span><span class="tok-o">),</span>
      <span class="tok-n">createTypeInformation</span><span class="tok-o">[</span><span class="tok-kt">Void</span><span class="tok-o">].</span><span class="tok-n">createSerializer</span><span class="tok-o">(</span><span class="tok-k">new</span> <span class="tok-nc">ExecutionConfig</span><span class="tok-o">))</span> <span class="tok-o">{</span>

  <span class="tok-k">var</span> <span class="tok-n">transactionWriter</span><span class="tok-k">:</span> <span class="tok-kt">BufferedWriter</span> <span class="tok-o">=</span> <span class="tok-k">_</span>

  <span class="tok-cm">/** Creates a temporary file for a transaction into which the records are</span>
<span class="tok-cm">    * written.</span>
<span class="tok-cm">    */</span>
  <span class="tok-k">override</span> <span class="tok-k">def</span> <span class="tok-n">beginTransaction</span><span class="tok-o">()</span><span class="tok-k">:</span> <span class="tok-kt">String</span> <span class="tok-o">=</span> <span class="tok-o">{</span>
    <span class="tok-c1">// path of transaction file is built from current time and task index</span>
    <span class="tok-k">val</span> <span class="tok-n">timeNow</span> <span class="tok-k">=</span> <span class="tok-nc">LocalDateTime</span><span class="tok-o">.</span><span class="tok-n">now</span><span class="tok-o">(</span><span class="tok-nc">ZoneId</span><span class="tok-o">.</span><span class="tok-n">of</span><span class="tok-o">(</span><span class="tok-s">&quot;UTC&quot;</span><span class="tok-o">))</span>
      <span class="tok-o">.</span><span class="tok-n">format</span><span class="tok-o">(</span><span class="tok-nc">DateTimeFormatter</span><span class="tok-o">.</span><span class="tok-nc">ISO_LOCAL_DATE_TIME</span><span class="tok-o">)</span>
    <span class="tok-k">val</span> <span class="tok-n">taskIdx</span> <span class="tok-k">=</span> <span class="tok-k">this</span><span class="tok-o">.</span><span class="tok-n">getRuntimeContext</span><span class="tok-o">.</span><span class="tok-n">getIndexOfThisSubtask</span>
    <span class="tok-k">val</span> <span class="tok-n">transactionFile</span> <span class="tok-k">=</span> <span class="tok-s">s&quot;</span><span class="tok-si">$timeNow</span><span class="tok-s">-</span><span class="tok-si">$taskIdx</span><span class="tok-s">&quot;</span>

    <span class="tok-c1">// create transaction file and writer</span>
    <span class="tok-k">val</span> <span class="tok-n">tFilePath</span> <span class="tok-k">=</span> <span class="tok-nc">Paths</span><span class="tok-o">.</span><span class="tok-n">get</span><span class="tok-o">(</span><span class="tok-s">s&quot;</span><span class="tok-si">$tempPath</span><span class="tok-s">/</span><span class="tok-si">$transactionFile</span><span class="tok-s">&quot;</span><span class="tok-o">)</span>
    <span class="tok-nc">Files</span><span class="tok-o">.</span><span class="tok-n">createFile</span><span class="tok-o">(</span><span class="tok-n">tFilePath</span><span class="tok-o">)</span>
    <span class="tok-k">this</span><span class="tok-o">.</span><span class="tok-n">transactionWriter</span> <span class="tok-k">=</span> <span class="tok-nc">Files</span><span class="tok-o">.</span><span class="tok-n">newBufferedWriter</span><span class="tok-o">(</span><span class="tok-n">tFilePath</span><span class="tok-o">)</span>
    <span class="tok-n">println</span><span class="tok-o">(</span><span class="tok-s">s&quot;Creating Transaction File: </span><span class="tok-si">$tFilePath</span><span class="tok-s">&quot;</span><span class="tok-o">)</span>
    <span class="tok-c1">// name of transaction file is returned to later identify the transaction</span>
    <span class="tok-n">transactionFile</span>
  <span class="tok-o">}</span>

  <span class="tok-cm">/** Write record into the current transaction file. */</span>
  <span class="tok-k">override</span> <span class="tok-k">def</span> <span class="tok-n">invoke</span><span class="tok-o">(</span>
      <span class="tok-n">transaction</span><span class="tok-k">:</span> <span class="tok-kt">String</span><span class="tok-o">,</span>
      <span class="tok-n">value</span><span class="tok-k">:</span> <span class="tok-o">(</span><span class="tok-kt">String</span><span class="tok-o">,</span> <span class="tok-kt">Double</span><span class="tok-o">),</span>
      <span class="tok-n">context</span><span class="tok-k">:</span> <span class="tok-kt">Context</span><span class="tok-o">[</span><span class="tok-k">_</span><span class="tok-o">])</span><span class="tok-k">:</span> <span class="tok-kt">Unit</span> <span class="tok-o">=</span> <span class="tok-o">{</span>
    <span class="tok-n">transactionWriter</span><span class="tok-o">.</span><span class="tok-n">write</span><span class="tok-o">(</span><span class="tok-n">value</span><span class="tok-o">.</span><span class="tok-n">toString</span><span class="tok-o">)</span>
    <span class="tok-n">transactionWriter</span><span class="tok-o">.</span><span class="tok-n">write</span><span class="tok-o">(</span><span class="tok-sc">&#39;\n&#39;</span><span class="tok-o">)</span>
  <span class="tok-o">}</span>

  <span class="tok-cm">/** Flush and close the current transaction file. */</span>
  <span class="tok-k">override</span> <span class="tok-k">def</span> <span class="tok-n">preCommit</span><span class="tok-o">(</span><span class="tok-n">transaction</span><span class="tok-k">:</span> <span class="tok-kt">String</span><span class="tok-o">)</span><span class="tok-k">:</span> <span class="tok-kt">Unit</span> <span class="tok-o">=</span> <span class="tok-o">{</span>
    <span class="tok-n">transactionWriter</span><span class="tok-o">.</span><span class="tok-n">flush</span><span class="tok-o">()</span>
    <span class="tok-n">transactionWriter</span><span class="tok-o">.</span><span class="tok-n">close</span><span class="tok-o">()</span>
  <span class="tok-o">}</span>

  <span class="tok-cm">/** Commit a transaction by moving the precommitted transaction file</span>
<span class="tok-cm">    * to the target directory.</span>
<span class="tok-cm">    */</span>
  <span class="tok-k">override</span> <span class="tok-k">def</span> <span class="tok-n">commit</span><span class="tok-o">(</span><span class="tok-n">transaction</span><span class="tok-k">:</span> <span class="tok-kt">String</span><span class="tok-o">)</span><span class="tok-k">:</span> <span class="tok-kt">Unit</span> <span class="tok-o">=</span> <span class="tok-o">{</span>
    <span class="tok-k">val</span> <span class="tok-n">tFilePath</span> <span class="tok-k">=</span> <span class="tok-nc">Paths</span><span class="tok-o">.</span><span class="tok-n">get</span><span class="tok-o">(</span><span class="tok-s">s&quot;</span><span class="tok-si">$tempPath</span><span class="tok-s">/</span><span class="tok-si">$transaction</span><span class="tok-s">&quot;</span><span class="tok-o">)</span>
    <span class="tok-c1">// check if the file exists to ensure that the commit is idempotent</span>
    <span class="tok-k">if</span> <span class="tok-o">(</span><span class="tok-nc">Files</span><span class="tok-o">.</span><span class="tok-n">exists</span><span class="tok-o">(</span><span class="tok-n">tFilePath</span><span class="tok-o">))</span> <span class="tok-o">{</span>
      <span class="tok-k">val</span> <span class="tok-n">cFilePath</span> <span class="tok-k">=</span> <span class="tok-nc">Paths</span><span class="tok-o">.</span><span class="tok-n">get</span><span class="tok-o">(</span><span class="tok-s">s&quot;</span><span class="tok-si">$targetPath</span><span class="tok-s">/</span><span class="tok-si">$transaction</span><span class="tok-s">&quot;</span><span class="tok-o">)</span>
      <span class="tok-nc">Files</span><span class="tok-o">.</span><span class="tok-n">move</span><span class="tok-o">(</span><span class="tok-n">tFilePath</span><span class="tok-o">,</span> <span class="tok-n">cFilePath</span><span class="tok-o">)</span>
    <span class="tok-o">}</span>
  <span class="tok-o">}</span>

  <span class="tok-cm">/** Aborts a transaction by deleting the transaction file. */</span>
  <span class="tok-k">override</span> <span class="tok-k">def</span> <span class="tok-n">abort</span><span class="tok-o">(</span><span class="tok-n">transaction</span><span class="tok-k">:</span> <span class="tok-kt">String</span><span class="tok-o">)</span><span class="tok-k">:</span> <span class="tok-kt">Unit</span> <span class="tok-o">=</span> <span class="tok-o">{</span>
    <span class="tok-k">val</span> <span class="tok-n">tFilePath</span> <span class="tok-k">=</span> <span class="tok-nc">Paths</span><span class="tok-o">.</span><span class="tok-n">get</span><span class="tok-o">(</span><span class="tok-s">s&quot;</span><span class="tok-si">$tempPath</span><span class="tok-s">/</span><span class="tok-si">$transaction</span><span class="tok-s">&quot;</span><span class="tok-o">)</span>
    <span class="tok-k">if</span> <span class="tok-o">(</span><span class="tok-nc">Files</span><span class="tok-o">.</span><span class="tok-n">exists</span><span class="tok-o">(</span><span class="tok-n">tFilePath</span><span class="tok-o">))</span> <span class="tok-o">{</span>
      <span class="tok-nc">Files</span><span class="tok-o">.</span><span class="tok-n">delete</span><span class="tok-o">(</span><span class="tok-n">tFilePath</span><span class="tok-o">)</span>
    <span class="tok-o">}</span>
  <span class="tok-o">}</span>
<span class="tok-o">}</span></code></pre>
</div>
</div>
<div class="paragraph">
<p>TwoPhaseCommitSinkFunction[IN, TXN, CONTEXT]包含如下三个范型参数：</p>
</div>
<div class="ulist">
<ul>
<li>
<p>IN表示输入数据的类型。</p>
</li>
<li>
<p>TXN定义了一个事务的标识符，可以用来识别和恢复事务。</p>
</li>
<li>
<p>CONTEXT定义了自定义的上下文。</p>
</li>
</ul>
</div>
<div class="paragraph">
<p>TwoPhaseCommitSinkFunction的构造器需要两个TypeSerializer。一个是TXN的类型，另一个是CONTEXT的类型。</p>
</div>
<div class="paragraph">
<p>最后，TwoPhaseCommitSinkFunction定义了五个需要实现的方法：</p>
</div>
<div class="ulist">
<ul>
<li>
<p>beginTransaction(): TXN开始一个事务，并返回事务的标识符。</p>
</li>
<li>
<p>invoke(txn: TXN, value: IN, context: Context[_]): Unit将值写入到当前事务中。</p>
</li>
<li>
<p>preCommit(txn: TXN): Unit预提交一个事务。一个预提交的事务不会接收新的写入。</p>
</li>
<li>
<p>commit(txn: TXN): Unit提交一个事务。这个操作必须是幂等的。</p>
</li>
<li>
<p>abort(txn: TXN): Unit终止一个事务。</p>
</li>
</ul>
</div>
</div>
</div>
</div>
</div>
<div class="sect1">
<h2 id="_flink部署与运维">9. Flink部署与运维</h2>
<div class="sectionbody">
<div class="sect2">
<h3 id="_部署方式">9.1. 部署方式</h3>
<div class="sect3">
<h4 id="_standalone集群">9.1.1. standalone集群</h4>
<div class="paragraph">
<p>standalone集群包含至少一个master进程，以及至少一个TaskManager进程，TaskManager进程运行在一台或者多台机器上。所有的进程都是JVM进程。下图展示了standalone集群的部署。</p>
</div>
<div class="imageblock">
<div class="content">
<img src="images/spaf_0901.png" alt="spaf 0901">
</div>
</div>
<div class="paragraph">
<p>master进程在不同的线程中运行了一个Dispatcher和一个ResourceManager。一旦它们开始运行，所有TaskManager都将在Resourcemanager中进行注册。下图展示了一个任务如何提交到一个standalone集群中去。</p>
</div>
<div class="imageblock">
<div class="content">
<img src="images/spaf_0902.png" alt="spaf 0902">
</div>
</div>
<div class="paragraph">
<p>客户端向Dispatcher提交了一个任务，Dispatcher将会启动一个JobManager线程，并提供执行所需的JobGraph。JobManager向ResourceManager请求必要的task slots。一旦请求的slots分配好，JobManager就会部署job。</p>
</div>
<div class="paragraph">
<p>在standalone这种部署方式中，master和worker进程在失败以后，并不会自动重启。如果有足够的slots可供使用，job是可以从一次worker失败中恢复的。只要我们运行多个worker就好了。但如果job想从master失败中恢复的话，则需要进行高可用(HA)的配置了。</p>
</div>
<div class="paragraph">
<p><strong>部署步骤</strong></p>
</div>
<div class="paragraph">
<p>下载压缩包</p>
</div>
<div class="paragraph">
<p>链接：http://mirror.bit.edu.cn/apache/flink/flink-1.10.0/flink-1.10.0-bin-scala_2.11.tgz</p>
</div>
<div class="paragraph">
<p>解压缩</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="pygments highlight"><code data-lang="shell"><span></span>tar xvfz flink-1.10.0-bin-scala_2.11.tgz</code></pre>
</div>
</div>
<div class="paragraph">
<p>启动集群</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="pygments highlight"><code data-lang="shell"><span></span><span class="tok-nb">cd</span> flink-1.10.0
./bin/start-cluster.sh</code></pre>
</div>
</div>
<div class="paragraph">
<p>检查集群状态可以访问：http://localhost:8081</p>
</div>
<div class="paragraph">
<p>部署分布式集群</p>
</div>
<div class="olist arabic">
<ol class="arabic">
<li>
<p>所有运行TaskManager的机器的主机名（或者IP地址）都需要写入<code>./conf/slaves</code>文件中。</p>
</li>
<li>
<p><code>start-cluster.sh</code>脚本需要所有机器的无密码的SSH登录配置，方便启动TaskManager进程。</p>
</li>
<li>
<p>Flink的文件夹在所有的机器上都需要有相同的绝对路径。</p>
</li>
<li>
<p>运行master进程的机器的主机名或者IP地址需要写在<code>./conf/flink-conf.yaml</code>文件的<code>jobmanager.rpc.address</code>配置项。</p>
</li>
</ol>
</div>
<div class="paragraph">
<p>一旦部署好，我们就可以调用<code>./bin/start-cluster.sh</code>命令启动集群了，脚本会在本地机器启动一个JobManager，然后在每个slave机器上启动一个TaskManager。停止运行，请使用<code>./bin/stop-cluster.sh</code>。</p>
</div>
</div>
<div class="sect3">
<h4 id="_apache_hadoop_yarn">9.1.2. Apache Hadoop Yarn</h4>
<div class="paragraph">
<p>YARN是Apache Hadoop的资源管理组件。用来计算集群环境所需要的CPU和内存资源，然后提供给应用程序请求的资源。</p>
</div>
<div class="paragraph">
<p>Flink can run on YARN in two modes: the job mode and the session mode. In job mode, a Flink cluster is started to run a single job. Once the job terminates, the Flink cluster is stopped and all resources are returned. Figure 9-3 shows how a Flink job is submitted to a YARN cluster.</p>
</div>
<div class="paragraph">
<p>Flink在YARN上运行，有两种模式：job模式和session模式。在job模式中，Flink集群用来运行一个单独的job。一旦job结束，Flink集群停止，并释放所有资源。下图展示了Flink的job如何提交到YARN集群。</p>
</div>
<div class="imageblock">
<div class="content">
<img src="images/spaf_0903.png" alt="spaf 0903">
</div>
</div>
<div class="paragraph">
<p>当客户端提交任务时，客户端将建立和YARN ResourceManager的连接，然后启动一个新的YARN应用的master进程，进程中包含一个JobManager线程和一个ResourceManager。JobManager向ResourceManager请求所需要的slots，用来运行Flink的job。接下来，Flink的ResourceManager将向Yarn的ResourceManager请求容器，然后启动TaskManager进程。一旦启动，TaskManager会将slots注册在Flink的ResourceManager中，Flink的ResourceManager将把slots提供给JobManager。最终，JobManager把job的任务提交给TaskManager执行。</p>
</div>
<div class="paragraph">
<p>sesison模式将启动一个长期运行的Flink集群，这个集群可以运行多个job，需要手动停止集群。如果以session模式启动，Flink将会连接到YARN的ResourceManager，然后启动一个master进程，包括一个Dispatcher线程和一个Flink的ResourceManager的线程。下图展示了一个Flink YARN session的启动。</p>
</div>
<div class="imageblock">
<div class="content">
<img src="images/spaf_0904.png" alt="spaf 0904">
</div>
</div>
<div class="paragraph">
<p>当一个job被提交运行，Dispatcher将启动一个JobManager线程，这个线程将向Flink的ResourceManager请求所需要的slots。如果没有足够的slots，Flink的ResourceManager将向YARN的ResourceManager请求额外的容器，来启动TaskManager进程，并在Flink的ResourceManager中注册。一旦所需slots可用，Flink的ResourceManager将吧slots分配给JobManager，然后开始执行job。下图展示了job如何在session模式下执行。</p>
</div>
<div class="imageblock">
<div class="content">
<img src="images/spaf_0905.png" alt="spaf 0905">
</div>
</div>
<div class="paragraph">
<p>无论使用job模式还是sesison模式，都需要能够访问Hadoop。</p>
</div>
<div class="paragraph">
<p>job模式可以用以下命令来提交任务：</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="pygments highlight"><code data-lang="shell"><span></span>./bin/flink run -m yarn-cluster ./path/to/job.jar</code></pre>
</div>
</div>
<div class="paragraph">
<p>session模式则是</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="pygments highlight"><code data-lang="shell"><span></span>./bin/yarn-session.sh
./bin/flink run ./path/to/job.jar</code></pre>
</div>
</div>
</div>
</div>
<div class="sect2">
<h3 id="_高可用配置ha">9.2. 高可用配置(HA)</h3>
<div class="paragraph">
<p>Flink的高可用配置需要Apache ZooKeeper组件，以及一个分布式文件系统，例如HDFS等等。JobManager将会把相关信息都存储在文件系统中，并将指向文件系统中相关信息的指针保存在ZooKeeper中。一旦失败，一个新的JobManager将从ZooKeeper中指向相关信息的指针所指向的文件系统中读取元数据，并恢复运行。</p>
</div>
<div class="paragraph">
<p>配置文件编写</p>
</div>
<div class="listingblock">
<div class="title">./conf/flink-conf.yaml</div>
<div class="content">
<pre class="pygments highlight"><code data-lang="yaml"><span></span><span class="tok-c1"># REQUIRED: enable HA mode via ZooKeeper high-availability: zookeeper</span>
<span class="tok-c1"># REQUIRED: provide a list of all ZooKeeper servers of the quorum</span>
<span class="tok-l tok-l-Scalar tok-l-Scalar-Plain">high-availability.zookeeper.quorum</span><span class="tok-p tok-p-Indicator">:</span> <span class="tok-l tok-l-Scalar tok-l-Scalar-Plain">address1:2181[,...],addressX:2181</span>
<span class="tok-c1"># REQUIRED: set storage location for job metadata in remote storage</span>
<span class="tok-l tok-l-Scalar tok-l-Scalar-Plain">high-availability.storageDir</span><span class="tok-p tok-p-Indicator">:</span> <span class="tok-l tok-l-Scalar tok-l-Scalar-Plain">hdfs:///flink/recovery</span>
<span class="tok-c1"># RECOMMENDED: set the base path for all Flink clusters in ZooKeeper.</span>
<span class="tok-c1"># Isolates Flink from other frameworks using the ZooKeeper cluster.</span>
<span class="tok-l tok-l-Scalar tok-l-Scalar-Plain">high-availability.zookeeper.path.root</span><span class="tok-p tok-p-Indicator">:</span> <span class="tok-l tok-l-Scalar tok-l-Scalar-Plain">/flink</span></code></pre>
</div>
</div>
<div class="sect3">
<h4 id="_standalone集群高可用配置">9.2.1. standalone集群高可用配置</h4>
<div class="paragraph">
<p>需要在配置文件中加一行集群标识符信息，因为可能多个集群共用一个zookeeper服务。</p>
</div>
<div class="listingblock">
<div class="title">./conf/flink-conf.yaml</div>
<div class="content">
<pre class="pygments highlight"><code data-lang="yaml"><span></span><span class="tok-c1"># RECOMMENDED: set the path for the Flink cluster in ZooKeeper.</span>
<span class="tok-c1"># Isolates multiple Flink clusters from each other.</span>
<span class="tok-c1"># The cluster id is required to look up the metadata of a failed cluster.</span>
<span class="tok-l tok-l-Scalar tok-l-Scalar-Plain">high-availability.cluster-id</span><span class="tok-p tok-p-Indicator">:</span> <span class="tok-l tok-l-Scalar tok-l-Scalar-Plain">/cluster-1</span></code></pre>
</div>
</div>
</div>
<div class="sect3">
<h4 id="_yarn集群高可用配置">9.2.2. yarn集群高可用配置</h4>
<div class="paragraph">
<p>首先在yarn集群的配置文件<code>yarn-site.xml</code>中加入以下代码</p>
</div>
<div class="listingblock">
<div class="title">yarn-site.xml</div>
<div class="content">
<pre class="pygments highlight"><code data-lang="xml"><span></span><span class="tok-nt">&lt;property&gt;</span>
  <span class="tok-nt">&lt;name&gt;</span>yarn.resourcemanager.am.max-attempts<span class="tok-nt">&lt;/name&gt;</span>
  <span class="tok-nt">&lt;value&gt;</span>4<span class="tok-nt">&lt;/value&gt;</span>
  <span class="tok-nt">&lt;description&gt;</span>
    The maximum number of application master execution attempts.
    Default value is 2, i.e., an application is restarted at most once.
  <span class="tok-nt">&lt;/description&gt;</span>
<span class="tok-nt">&lt;/property&gt;</span></code></pre>
</div>
</div>
<div class="paragraph">
<p>然后在<code>./conf/flink-conf.yaml</code>加上</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="pygments highlight"><code data-lang="yaml"><span></span><span class="tok-c1"># Restart an application at most 3 times (+ the initial start).</span>
<span class="tok-c1"># Must be less or equal to the configured maximum number of attempts.</span>
<span class="tok-l tok-l-Scalar tok-l-Scalar-Plain">yarn.application-attempts</span><span class="tok-p tok-p-Indicator">:</span> <span class="tok-l tok-l-Scalar tok-l-Scalar-Plain">4</span></code></pre>
</div>
</div>
</div>
</div>
<div class="sect2">
<h3 id="_与hadoop集成">9.3. 与Hadoop集成</h3>
<div class="paragraph">
<p>推荐两种方法</p>
</div>
<div class="olist arabic">
<ol class="arabic">
<li>
<p>下载包含hadoop的Flink版本。</p>
</li>
<li>
<p>使用我们之前下载的Flink，然后配置Hadoop的环境变量。<code>export HADOOP_CLASSPATH=<code>hadoop classpath</code></code></p>
</li>
</ol>
</div>
<div class="paragraph">
<p>我们还需要提供Hadoop配置文件的路径。只需设置名为<code>HADOOP_CONF_DIR</code>的环境变量就可以了。这样Flink就能够连上YARN的ResourceManager和HDFS了。</p>
</div>
</div>
<div class="sect2">
<h3 id="_保存点操作">9.4. 保存点操作</h3>
<div class="listingblock">
<div class="content">
<pre class="pygments highlight"><code data-lang="shell"><span></span>./bin/flink savepoint &lt;jobId&gt; <span class="tok-o">[</span>savepointPath<span class="tok-o">]</span></code></pre>
</div>
</div>
<div class="paragraph">
<p>例如</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="pygments highlight"><code data-lang="shell"><span></span>./bin/flink savepoint bc0b2ad61ecd4a615d92ce25390f61ad <span class="tok-se">\</span>
hdfs:///xxx:50070/savepoints
Triggering savepoint <span class="tok-k">for</span> job bc0b2ad61ecd4a615d92ce25390f61ad.
Waiting <span class="tok-k">for</span> response...
Savepoint completed.
Path: hdfs:///xxx:50070/savepoints/savepoint-bc0b2a-63cf5d5ccef8
You can resume your program from this savepoint with the run command.</code></pre>
</div>
</div>
<div class="paragraph">
<p>删除保存点文件</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="pygments highlight"><code data-lang="shell"><span></span>./bin/flink savepoint -d &lt;savepointPath&gt;</code></pre>
</div>
</div>
<div class="paragraph">
<p>例子</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="pygments highlight"><code data-lang="shell"><span></span>./bin/flink savepoint -d <span class="tok-se">\</span>
hdfs:///xxx:50070/savepoints/savepoint-bc0b2a-63cf5d5ccef8
Disposing savepoint <span class="tok-s1">&#39;hdfs:///xxx:50070/savepoints/savepoint-bc0b2a-63cf5d5ccef8&#39;</span>.
Waiting <span class="tok-k">for</span> response...
​Savepoint <span class="tok-s1">&#39;hdfs:///xxx:50070/savepoints/savepoint-bc0b2a-63cf5d5ccef8&#39;</span> disposed.</code></pre>
</div>
</div>
</div>
<div class="sect2">
<h3 id="_取消一个应用">9.5. 取消一个应用</h3>
<div class="listingblock">
<div class="content">
<pre class="pygments highlight"><code data-lang="shell"><span></span>./bin/flink cancel &lt;jobId&gt;</code></pre>
</div>
</div>
<div class="paragraph">
<p>取消的同时做保存点操作</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="pygments highlight"><code data-lang="shell"><span></span>./bin/flink cancel -s <span class="tok-o">[</span>savepointPath<span class="tok-o">]</span> &lt;jobId&gt;</code></pre>
</div>
</div>
<div class="paragraph">
<p>例如</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="pygments highlight"><code data-lang="shell"><span></span>./bin/flink cancel -s <span class="tok-se">\</span>
hdfs:///xxx:50070/savepoints d5fdaff43022954f5f02fcd8f25ef855
Cancelling job bc0b2ad61ecd4a615d92ce25390f61ad
with savepoint to hdfs:///xxx:50070/savepoints.
Cancelled job bc0b2ad61ecd4a615d92ce25390f61ad.
Savepoint stored in hdfs:///xxx:50070/savepoints/savepoint-bc0b2a-d08de07fbb10.</code></pre>
</div>
</div>
</div>
<div class="sect2">
<h3 id="_从保存点启动应用程序_2">9.6. 从保存点启动应用程序</h3>
<div class="listingblock">
<div class="content">
<pre class="pygments highlight"><code data-lang="shell"><span></span>./bin/flink run -s &lt;savepointPath&gt; <span class="tok-o">[</span>options<span class="tok-o">]</span> &lt;jobJar&gt; <span class="tok-o">[</span>arguments<span class="tok-o">]</span></code></pre>
</div>
</div>
</div>
<div class="sect2">
<h3 id="_扩容改变并行度操作">9.7. 扩容，改变并行度操作</h3>
<div class="listingblock">
<div class="content">
<pre class="pygments highlight"><code data-lang="shell"><span></span>./bin/flink modify &lt;jobId&gt; -p &lt;newParallelism&gt;</code></pre>
</div>
</div>
<div class="paragraph">
<p>例子</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="pygments highlight"><code data-lang="shell"><span></span>./bin/flink modify bc0b2ad61ecd4a615d92ce25390f61ad -p <span class="tok-m">16</span>
Modify job bc0b2ad61ecd4a615d92ce25390f61ad.
​Rescaled job bc0b2ad61ecd4a615d92ce25390f61ad. Its new parallelism is <span class="tok-m">16</span>.</code></pre>
</div>
</div>
</div>
</div>
</div>
<div class="sect1">
<h2 id="_flink_cep简介">10. Flink CEP简介</h2>
<div class="sectionbody">
<div class="paragraph">
<p><strong>什么是复杂事件CEP？</strong></p>
</div>
<div class="paragraph">
<p>一个或多个由简单事件构成的事件流通过一定的规则匹配，然后输出用户想得到的数据，满足规则的复杂事件。</p>
</div>
<div class="paragraph">
<p><strong>特征：</strong></p>
</div>
<div class="ulist">
<ul>
<li>
<p>目标：从有序的简单事件流中发现一些高阶特征</p>
</li>
<li>
<p>输入：一个或多个由简单事件构成的事件流</p>
</li>
<li>
<p>处理：识别简单事件之间的内在联系，多个符合一定规则的简单事件构成复杂事件</p>
</li>
<li>
<p>输出：满足规则的复杂事件</p>
</li>
</ul>
</div>
<div class="imageblock">
<div class="content">
<img src="images/cep1.jpg" alt="cep1">
</div>
</div>
<div class="paragraph">
<p>CEP用于分析低延迟、频繁产生的不同来源的事件流。CEP可以帮助在复杂的、不相关的事件流中找出有意义的模式和复杂的关系，以接近实时或准实时的获得通知并阻止一些行为。</p>
</div>
<div class="paragraph">
<p>CEP支持在流上进行模式匹配，根据模式的条件不同，分为连续的条件或不连续的条件；模式的条件允许有时间的限制，当在条件范围内没有达到满足的条件时，会导致模式匹配超时。</p>
</div>
<div class="paragraph">
<p>看起来很简单，但是它有很多不同的功能：</p>
</div>
<div class="ulist">
<ul>
<li>
<p>输入的流数据，尽快产生结果</p>
</li>
<li>
<p>在2个event流上，基于时间进行聚合类的计算</p>
</li>
<li>
<p>提供实时/准实时的警告和通知</p>
</li>
<li>
<p>在多样的数据源中产生关联并分析模式</p>
</li>
<li>
<p>高吞吐、低延迟的处理</p>
</li>
</ul>
</div>
<div class="paragraph">
<p>市场上有多种CEP的解决方案，例如Spark、Samza、Beam等，但他们都没有提供专门的library支持。但是Flink提供了专门的CEP library。</p>
</div>
<div class="paragraph">
<p><strong>Flink CEP</strong></p>
</div>
<div class="paragraph">
<p>Flink为CEP提供了专门的Flink CEP library，它包含如下组件：</p>
</div>
<div class="ulist">
<ul>
<li>
<p>Event Stream</p>
</li>
<li>
<p>pattern定义</p>
</li>
<li>
<p>pattern检测</p>
</li>
<li>
<p>生成Alert</p>
</li>
</ul>
</div>
<div class="imageblock">
<div class="content">
<img src="images/cep6.png" alt="cep6">
</div>
</div>
<div class="paragraph">
<p>首先，开发人员要在DataStream流上定义出模式条件，之后Flink CEP引擎进行模式检测，必要时生成告警。</p>
</div>
<div class="paragraph">
<p>为了使用Flink CEP，我们需要导入依赖：</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="pygments highlight"><code data-lang="xml"><span></span><span class="tok-nt">&lt;dependency&gt;</span>
  <span class="tok-nt">&lt;groupId&gt;</span>org.apache.flink<span class="tok-nt">&lt;/groupId&gt;</span>
  <span class="tok-nt">&lt;artifactId&gt;</span>flink-cep-scala_${scala.binary.version}<span class="tok-nt">&lt;/artifactId&gt;</span>
  <span class="tok-nt">&lt;version&gt;</span>${flink.version}<span class="tok-nt">&lt;/version&gt;</span>
<span class="tok-nt">&lt;/dependency&gt;</span></code></pre>
</div>
</div>
<div class="paragraph">
<p><strong>Event Streams</strong></p>
</div>
<div class="paragraph">
<p>登录事件流</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="pygments highlight"><code data-lang="scala"><span></span><span class="tok-k">case</span> <span class="tok-k">class</span> <span class="tok-nc">LoginEvent</span><span class="tok-o">(</span><span class="tok-n">userId</span><span class="tok-k">:</span> <span class="tok-kt">String</span><span class="tok-o">,</span> <span class="tok-n">ip</span><span class="tok-k">:</span> <span class="tok-kt">String</span><span class="tok-o">,</span> <span class="tok-n">eventType</span><span class="tok-k">:</span> <span class="tok-kt">String</span><span class="tok-o">,</span> <span class="tok-n">eventTime</span><span class="tok-k">:</span> <span class="tok-kt">String</span><span class="tok-o">)</span>

<span class="tok-k">val</span> <span class="tok-n">env</span> <span class="tok-k">=</span> <span class="tok-nc">StreamExecutionEnvironment</span><span class="tok-o">.</span><span class="tok-n">getExecutionEnvironment</span>
<span class="tok-n">env</span><span class="tok-o">.</span><span class="tok-n">setStreamTimeCharacteristic</span><span class="tok-o">(</span><span class="tok-nc">TimeCharacteristic</span><span class="tok-o">.</span><span class="tok-nc">EventTime</span><span class="tok-o">)</span>
<span class="tok-n">env</span><span class="tok-o">.</span><span class="tok-n">setParallelism</span><span class="tok-o">(</span><span class="tok-mi">1</span><span class="tok-o">)</span>

<span class="tok-k">val</span> <span class="tok-n">loginEventStream</span> <span class="tok-k">=</span> <span class="tok-n">env</span><span class="tok-o">.</span><span class="tok-n">fromCollection</span><span class="tok-o">(</span><span class="tok-nc">List</span><span class="tok-o">(</span>
  <span class="tok-nc">LoginEvent</span><span class="tok-o">(</span><span class="tok-s">&quot;1&quot;</span><span class="tok-o">,</span> <span class="tok-s">&quot;192.168.0.1&quot;</span><span class="tok-o">,</span> <span class="tok-s">&quot;fail&quot;</span><span class="tok-o">,</span> <span class="tok-s">&quot;1558430842&quot;</span><span class="tok-o">),</span>
  <span class="tok-nc">LoginEvent</span><span class="tok-o">(</span><span class="tok-s">&quot;1&quot;</span><span class="tok-o">,</span> <span class="tok-s">&quot;192.168.0.2&quot;</span><span class="tok-o">,</span> <span class="tok-s">&quot;fail&quot;</span><span class="tok-o">,</span> <span class="tok-s">&quot;1558430843&quot;</span><span class="tok-o">),</span>
  <span class="tok-nc">LoginEvent</span><span class="tok-o">(</span><span class="tok-s">&quot;1&quot;</span><span class="tok-o">,</span> <span class="tok-s">&quot;192.168.0.3&quot;</span><span class="tok-o">,</span> <span class="tok-s">&quot;fail&quot;</span><span class="tok-o">,</span> <span class="tok-s">&quot;1558430844&quot;</span><span class="tok-o">),</span>
  <span class="tok-nc">LoginEvent</span><span class="tok-o">(</span><span class="tok-s">&quot;2&quot;</span><span class="tok-o">,</span> <span class="tok-s">&quot;192.168.10.10&quot;</span><span class="tok-o">,</span> <span class="tok-s">&quot;success&quot;</span><span class="tok-o">,</span> <span class="tok-s">&quot;1558430845&quot;</span><span class="tok-o">)</span>
<span class="tok-o">)).</span><span class="tok-n">assignAscendingTimestamps</span><span class="tok-o">(</span><span class="tok-k">_</span><span class="tok-o">.</span><span class="tok-n">eventTime</span><span class="tok-o">.</span><span class="tok-n">toLong</span> <span class="tok-o">*</span> <span class="tok-mi">1000</span><span class="tok-o">)</span></code></pre>
</div>
</div>
<div class="paragraph">
<p><strong>Pattern API</strong></p>
</div>
<div class="paragraph">
<p>每个Pattern都应该包含几个步骤，或者叫做state。从一个state到另一个state，通常我们需要定义一些条件，例如下列的代码：</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="pygments highlight"><code data-lang="scala"><span></span><span class="tok-k">val</span> <span class="tok-n">loginFailPattern</span> <span class="tok-k">=</span> <span class="tok-nc">Pattern</span><span class="tok-o">.</span><span class="tok-n">begin</span><span class="tok-o">[</span><span class="tok-kt">LoginEvent</span><span class="tok-o">](</span><span class="tok-s">&quot;begin&quot;</span><span class="tok-o">)</span>
  <span class="tok-o">.</span><span class="tok-n">where</span><span class="tok-o">(</span><span class="tok-k">_</span><span class="tok-o">.</span><span class="tok-n">eventType</span><span class="tok-o">.</span><span class="tok-n">equals</span><span class="tok-o">(</span><span class="tok-s">&quot;fail&quot;</span><span class="tok-o">))</span>
  <span class="tok-o">.</span><span class="tok-n">next</span><span class="tok-o">(</span><span class="tok-s">&quot;next&quot;</span><span class="tok-o">)</span>
  <span class="tok-o">.</span><span class="tok-n">where</span><span class="tok-o">(</span><span class="tok-k">_</span><span class="tok-o">.</span><span class="tok-n">eventType</span><span class="tok-o">.</span><span class="tok-n">equals</span><span class="tok-o">(</span><span class="tok-s">&quot;fail&quot;</span><span class="tok-o">))</span>
  <span class="tok-o">.</span><span class="tok-n">within</span><span class="tok-o">(</span><span class="tok-nc">Time</span><span class="tok-o">.</span><span class="tok-n">seconds</span><span class="tok-o">(</span><span class="tok-mi">10</span><span class="tok-o">)</span></code></pre>
</div>
</div>
<div class="paragraph">
<p>每个state都应该有一个标示：</p>
</div>
<div class="paragraph">
<p>例如: <code>.begin[LoginEvent]("begin")</code>中的"begin"</p>
</div>
<div class="paragraph">
<p>每个state都需要有一个唯一的名字，而且需要一个filter来过滤条件，这个过滤条件定义事件需要符合的条件</p>
</div>
<div class="paragraph">
<p>例如: <code>.where(_.eventType.equals("fail"))</code></p>
</div>
<div class="paragraph">
<p>我们也可以通过subtype来限制event的子类型：</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="pygments highlight"><code data-lang="scala"><span></span><span class="tok-n">start</span><span class="tok-o">.</span><span class="tok-n">subtype</span><span class="tok-o">(</span><span class="tok-nc">SubEvent</span><span class="tok-o">.</span><span class="tok-n">class</span><span class="tok-o">).</span><span class="tok-n">where</span><span class="tok-o">(...);</span></code></pre>
</div>
</div>
<div class="paragraph">
<p>事实上，你可以多次调用subtype和where方法；而且如果where条件是不相关的，你可以通过or来指定一个单独的filter函数：</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="pygments highlight"><code data-lang="scala"><span></span><span class="tok-n">pattern</span><span class="tok-o">.</span><span class="tok-n">where</span><span class="tok-o">(...).</span><span class="tok-n">or</span><span class="tok-o">(...);</span></code></pre>
</div>
</div>
<div class="paragraph">
<p>之后，我们可以在此条件基础上，通过next或者followedBy方法切换到下一个state，next的意思是说上一步符合条件的元素之后紧挨着的元素；而followedBy并不要求一定是挨着的元素。这两者分别称为严格近邻和非严格近邻。</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="pygments highlight"><code data-lang="scala"><span></span><span class="tok-k">val</span> <span class="tok-n">strictNext</span> <span class="tok-k">=</span> <span class="tok-n">start</span><span class="tok-o">.</span><span class="tok-n">next</span><span class="tok-o">(</span><span class="tok-s">&quot;middle&quot;</span><span class="tok-o">)</span>
<span class="tok-k">val</span> <span class="tok-n">nonStrictNext</span> <span class="tok-k">=</span> <span class="tok-n">start</span><span class="tok-o">.</span><span class="tok-n">followedBy</span><span class="tok-o">(</span><span class="tok-s">&quot;middle&quot;</span><span class="tok-o">)</span></code></pre>
</div>
</div>
<div class="paragraph">
<p>最后，我们可以将所有的Pattern的条件限定在一定的时间范围内：</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="pygments highlight"><code data-lang="scala"><span></span><span class="tok-n">next</span><span class="tok-o">.</span><span class="tok-n">within</span><span class="tok-o">(</span><span class="tok-nc">Time</span><span class="tok-o">.</span><span class="tok-n">seconds</span><span class="tok-o">(</span><span class="tok-mi">10</span><span class="tok-o">))</span></code></pre>
</div>
</div>
<div class="paragraph">
<p>这个时间可以是Processing Time，也可以是Event Time。</p>
</div>
<div class="paragraph">
<p><strong>Pattern 检测</strong></p>
</div>
<div class="paragraph">
<p>通过一个input DataStream以及刚刚我们定义的Pattern，我们可以创建一个PatternStream：</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="pygments highlight"><code data-lang="scala"><span></span><span class="tok-k">val</span> <span class="tok-n">input</span> <span class="tok-k">=</span> <span class="tok-o">...</span>
<span class="tok-k">val</span> <span class="tok-n">pattern</span> <span class="tok-k">=</span> <span class="tok-o">...</span>

<span class="tok-k">val</span> <span class="tok-n">patternStream</span> <span class="tok-k">=</span> <span class="tok-nc">CEP</span><span class="tok-o">.</span><span class="tok-n">pattern</span><span class="tok-o">(</span><span class="tok-n">input</span><span class="tok-o">,</span> <span class="tok-n">pattern</span><span class="tok-o">)</span></code></pre>
</div>
</div>
<div class="listingblock">
<div class="content">
<pre class="pygments highlight"><code data-lang="scala"><span></span><span class="tok-k">val</span> <span class="tok-n">patternStream</span> <span class="tok-k">=</span> <span class="tok-nc">CEP</span><span class="tok-o">.</span><span class="tok-n">pattern</span><span class="tok-o">(</span><span class="tok-n">loginEventStream</span><span class="tok-o">.</span><span class="tok-n">keyBy</span><span class="tok-o">(</span><span class="tok-k">_</span><span class="tok-o">.</span><span class="tok-n">userId</span><span class="tok-o">),</span> <span class="tok-n">loginFailPattern</span><span class="tok-o">)</span></code></pre>
</div>
</div>
<div class="paragraph">
<p>一旦获得PatternStream，我们就可以通过select或flatSelect，从一个Map序列找到我们需要的告警信息。</p>
</div>
<div class="paragraph">
<p><strong>select</strong></p>
</div>
<div class="paragraph">
<p>select方法需要实现一个PatternSelectFunction，通过select方法来输出需要的警告。它接受一个Map对，包含string/event，其中key为state的名字，event则为真是的Event。</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="pygments highlight"><code data-lang="scala"><span></span><span class="tok-k">val</span> <span class="tok-n">loginFailDataStream</span> <span class="tok-k">=</span> <span class="tok-n">patternStream</span>
  <span class="tok-o">.</span><span class="tok-n">select</span><span class="tok-o">((</span><span class="tok-n">pattern</span><span class="tok-k">:</span> <span class="tok-kt">Map</span><span class="tok-o">[</span><span class="tok-kt">String</span>, <span class="tok-kt">Iterable</span><span class="tok-o">[</span><span class="tok-kt">LoginEvent</span><span class="tok-o">]])</span> <span class="tok-k">=&gt;</span> <span class="tok-o">{</span>
    <span class="tok-k">val</span> <span class="tok-n">first</span> <span class="tok-k">=</span> <span class="tok-n">pattern</span><span class="tok-o">.</span><span class="tok-n">getOrElse</span><span class="tok-o">(</span><span class="tok-s">&quot;begin&quot;</span><span class="tok-o">,</span> <span class="tok-kc">null</span><span class="tok-o">).</span><span class="tok-n">iterator</span><span class="tok-o">.</span><span class="tok-n">next</span><span class="tok-o">()</span>
    <span class="tok-k">val</span> <span class="tok-n">second</span> <span class="tok-k">=</span> <span class="tok-n">pattern</span><span class="tok-o">.</span><span class="tok-n">getOrElse</span><span class="tok-o">(</span><span class="tok-s">&quot;next&quot;</span><span class="tok-o">,</span> <span class="tok-kc">null</span><span class="tok-o">).</span><span class="tok-n">iterator</span><span class="tok-o">.</span><span class="tok-n">next</span><span class="tok-o">()</span>

    <span class="tok-o">(</span><span class="tok-n">second</span><span class="tok-o">.</span><span class="tok-n">userId</span><span class="tok-o">,</span> <span class="tok-n">second</span><span class="tok-o">.</span><span class="tok-n">ip</span><span class="tok-o">,</span> <span class="tok-n">second</span><span class="tok-o">.</span><span class="tok-n">eventType</span><span class="tok-o">)</span>
  <span class="tok-o">})</span></code></pre>
</div>
</div>
<div class="paragraph">
<p>其返回值仅为1条记录。</p>
</div>
<div class="paragraph">
<p><strong>flatSelect</strong></p>
</div>
<div class="paragraph">
<p>通过实现PatternFlatSelectFunction，实现与select相似的功能。唯一的区别就是flatSelect方法可以返回多条记录。</p>
</div>
<div class="paragraph">
<p><strong>超时事件的处理</strong></p>
</div>
<div class="paragraph">
<p>通过within方法，我们的parttern规则限定在一定的窗口范围内。当有超过窗口时间后还到达的event，我们可以通过在select或flatSelect中，实现PatternTimeoutFunction/PatternFlatTimeoutFunction来处理这种情况。</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="pygments highlight"><code data-lang="scala"><span></span><span class="tok-k">val</span> <span class="tok-n">complexResult</span> <span class="tok-k">=</span> <span class="tok-n">patternStream</span><span class="tok-o">.</span><span class="tok-n">select</span><span class="tok-o">(</span><span class="tok-n">orderTimeoutOutput</span><span class="tok-o">)</span> <span class="tok-o">{</span>
  <span class="tok-o">(</span><span class="tok-n">pattern</span><span class="tok-k">:</span> <span class="tok-kt">Map</span><span class="tok-o">[</span><span class="tok-kt">String</span>, <span class="tok-kt">Iterable</span><span class="tok-o">[</span><span class="tok-kt">OrderEvent</span><span class="tok-o">]],</span> <span class="tok-n">timestamp</span><span class="tok-k">:</span> <span class="tok-kt">Long</span><span class="tok-o">)</span> <span class="tok-k">=&gt;</span> <span class="tok-o">{</span>
    <span class="tok-k">val</span> <span class="tok-n">createOrder</span> <span class="tok-k">=</span> <span class="tok-n">pattern</span><span class="tok-o">.</span><span class="tok-n">get</span><span class="tok-o">(</span><span class="tok-s">&quot;begin&quot;</span><span class="tok-o">)</span>
    <span class="tok-nc">OrderTimeoutEvent</span><span class="tok-o">(</span><span class="tok-n">createOrder</span><span class="tok-o">.</span><span class="tok-n">get</span><span class="tok-o">.</span><span class="tok-n">iterator</span><span class="tok-o">.</span><span class="tok-n">next</span><span class="tok-o">().</span><span class="tok-n">orderId</span><span class="tok-o">,</span> <span class="tok-s">&quot;timeout&quot;</span><span class="tok-o">)</span>
  <span class="tok-o">}</span>
<span class="tok-o">}</span> <span class="tok-o">{</span>
  <span class="tok-n">pattern</span><span class="tok-k">:</span> <span class="tok-kt">Map</span><span class="tok-o">[</span><span class="tok-kt">String</span>, <span class="tok-kt">Iterable</span><span class="tok-o">[</span><span class="tok-kt">OrderEvent</span><span class="tok-o">]]</span> <span class="tok-k">=&gt;</span> <span class="tok-o">{</span>
    <span class="tok-k">val</span> <span class="tok-n">payOrder</span> <span class="tok-k">=</span> <span class="tok-n">pattern</span><span class="tok-o">.</span><span class="tok-n">get</span><span class="tok-o">(</span><span class="tok-s">&quot;next&quot;</span><span class="tok-o">)</span>
    <span class="tok-nc">OrderTimeoutEvent</span><span class="tok-o">(</span><span class="tok-n">payOrder</span><span class="tok-o">.</span><span class="tok-n">get</span><span class="tok-o">.</span><span class="tok-n">iterator</span><span class="tok-o">.</span><span class="tok-n">next</span><span class="tok-o">().</span><span class="tok-n">orderId</span><span class="tok-o">,</span> <span class="tok-s">&quot;success&quot;</span><span class="tok-o">)</span>
  <span class="tok-o">}</span>
<span class="tok-o">}</span>

<span class="tok-k">val</span> <span class="tok-n">timeoutResult</span> <span class="tok-k">=</span> <span class="tok-n">complexResult</span><span class="tok-o">.</span><span class="tok-n">getSideOutput</span><span class="tok-o">(</span><span class="tok-n">orderTimeoutOutput</span><span class="tok-o">)</span>

<span class="tok-n">complexResult</span><span class="tok-o">.</span><span class="tok-n">print</span><span class="tok-o">()</span>
<span class="tok-n">timeoutResult</span><span class="tok-o">.</span><span class="tok-n">print</span><span class="tok-o">()</span></code></pre>
</div>
</div>
<div class="paragraph">
<p>完整例子:</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="pygments highlight"><code data-lang="scala"><span></span><span class="tok-k">import</span> <span class="tok-nn">org.apache.flink.cep.scala.CEP</span>
<span class="tok-k">import</span> <span class="tok-nn">org.apache.flink.cep.scala.pattern.Pattern</span>
<span class="tok-k">import</span> <span class="tok-nn">org.apache.flink.streaming.api.TimeCharacteristic</span>
<span class="tok-k">import</span> <span class="tok-nn">org.apache.flink.streaming.api.scala._</span>
<span class="tok-k">import</span> <span class="tok-nn">org.apache.flink.streaming.api.windowing.time.Time</span>

<span class="tok-k">import</span> <span class="tok-nn">scala.collection.Map</span>

<span class="tok-k">object</span> <span class="tok-nc">ScalaFlinkLoginFail</span> <span class="tok-o">{</span>

  <span class="tok-k">def</span> <span class="tok-n">main</span><span class="tok-o">(</span><span class="tok-n">args</span><span class="tok-k">:</span> <span class="tok-kt">Array</span><span class="tok-o">[</span><span class="tok-kt">String</span><span class="tok-o">])</span><span class="tok-k">:</span> <span class="tok-kt">Unit</span> <span class="tok-o">=</span> <span class="tok-o">{</span>

    <span class="tok-k">val</span> <span class="tok-n">env</span> <span class="tok-k">=</span> <span class="tok-nc">StreamExecutionEnvironment</span><span class="tok-o">.</span><span class="tok-n">getExecutionEnvironment</span>
    <span class="tok-n">env</span><span class="tok-o">.</span><span class="tok-n">setStreamTimeCharacteristic</span><span class="tok-o">(</span><span class="tok-nc">TimeCharacteristic</span><span class="tok-o">.</span><span class="tok-nc">EventTime</span><span class="tok-o">)</span>
    <span class="tok-n">env</span><span class="tok-o">.</span><span class="tok-n">setParallelism</span><span class="tok-o">(</span><span class="tok-mi">1</span><span class="tok-o">)</span>

    <span class="tok-k">val</span> <span class="tok-n">loginEventStream</span> <span class="tok-k">=</span> <span class="tok-n">env</span><span class="tok-o">.</span><span class="tok-n">fromCollection</span><span class="tok-o">(</span><span class="tok-nc">List</span><span class="tok-o">(</span>
      <span class="tok-nc">LoginEvent</span><span class="tok-o">(</span><span class="tok-s">&quot;1&quot;</span><span class="tok-o">,</span> <span class="tok-s">&quot;192.168.0.1&quot;</span><span class="tok-o">,</span> <span class="tok-s">&quot;fail&quot;</span><span class="tok-o">,</span> <span class="tok-s">&quot;1558430842&quot;</span><span class="tok-o">),</span>
      <span class="tok-nc">LoginEvent</span><span class="tok-o">(</span><span class="tok-s">&quot;1&quot;</span><span class="tok-o">,</span> <span class="tok-s">&quot;192.168.0.2&quot;</span><span class="tok-o">,</span> <span class="tok-s">&quot;fail&quot;</span><span class="tok-o">,</span> <span class="tok-s">&quot;1558430843&quot;</span><span class="tok-o">),</span>
      <span class="tok-nc">LoginEvent</span><span class="tok-o">(</span><span class="tok-s">&quot;1&quot;</span><span class="tok-o">,</span> <span class="tok-s">&quot;192.168.0.3&quot;</span><span class="tok-o">,</span> <span class="tok-s">&quot;fail&quot;</span><span class="tok-o">,</span> <span class="tok-s">&quot;1558430844&quot;</span><span class="tok-o">),</span>
      <span class="tok-nc">LoginEvent</span><span class="tok-o">(</span><span class="tok-s">&quot;2&quot;</span><span class="tok-o">,</span> <span class="tok-s">&quot;192.168.10.10&quot;</span><span class="tok-o">,</span> <span class="tok-s">&quot;success&quot;</span><span class="tok-o">,</span> <span class="tok-s">&quot;1558430845&quot;</span><span class="tok-o">)</span>
    <span class="tok-o">)).</span><span class="tok-n">assignAscendingTimestamps</span><span class="tok-o">(</span><span class="tok-k">_</span><span class="tok-o">.</span><span class="tok-n">eventTime</span><span class="tok-o">.</span><span class="tok-n">toLong</span><span class="tok-o">)</span>

    <span class="tok-k">val</span> <span class="tok-n">loginFailPattern</span> <span class="tok-k">=</span> <span class="tok-nc">Pattern</span><span class="tok-o">.</span><span class="tok-n">begin</span><span class="tok-o">[</span><span class="tok-kt">LoginEvent</span><span class="tok-o">](</span><span class="tok-s">&quot;begin&quot;</span><span class="tok-o">)</span>
      <span class="tok-o">.</span><span class="tok-n">where</span><span class="tok-o">(</span><span class="tok-k">_</span><span class="tok-o">.</span><span class="tok-n">eventType</span><span class="tok-o">.</span><span class="tok-n">equals</span><span class="tok-o">(</span><span class="tok-s">&quot;fail&quot;</span><span class="tok-o">))</span>
      <span class="tok-o">.</span><span class="tok-n">next</span><span class="tok-o">(</span><span class="tok-s">&quot;next&quot;</span><span class="tok-o">)</span>
      <span class="tok-o">.</span><span class="tok-n">where</span><span class="tok-o">(</span><span class="tok-k">_</span><span class="tok-o">.</span><span class="tok-n">eventType</span><span class="tok-o">.</span><span class="tok-n">equals</span><span class="tok-o">(</span><span class="tok-s">&quot;fail&quot;</span><span class="tok-o">))</span>
      <span class="tok-o">.</span><span class="tok-n">within</span><span class="tok-o">(</span><span class="tok-nc">Time</span><span class="tok-o">.</span><span class="tok-n">seconds</span><span class="tok-o">(</span><span class="tok-mi">10</span><span class="tok-o">))</span>

    <span class="tok-k">val</span> <span class="tok-n">patternStream</span> <span class="tok-k">=</span> <span class="tok-nc">CEP</span><span class="tok-o">.</span><span class="tok-n">pattern</span><span class="tok-o">(</span><span class="tok-n">loginEventStream</span><span class="tok-o">.</span><span class="tok-n">keyBy</span><span class="tok-o">(</span><span class="tok-k">_</span><span class="tok-o">.</span><span class="tok-n">userId</span><span class="tok-o">),</span> <span class="tok-n">loginFailPattern</span><span class="tok-o">)</span>

    <span class="tok-k">val</span> <span class="tok-n">loginFailDataStream</span> <span class="tok-k">=</span> <span class="tok-n">patternStream</span>
      <span class="tok-o">.</span><span class="tok-n">select</span><span class="tok-o">((</span><span class="tok-n">pattern</span><span class="tok-k">:</span> <span class="tok-kt">Map</span><span class="tok-o">[</span><span class="tok-kt">String</span>, <span class="tok-kt">Iterable</span><span class="tok-o">[</span><span class="tok-kt">LoginEvent</span><span class="tok-o">]])</span> <span class="tok-k">=&gt;</span> <span class="tok-o">{</span>
        <span class="tok-k">val</span> <span class="tok-n">first</span> <span class="tok-k">=</span> <span class="tok-n">pattern</span><span class="tok-o">.</span><span class="tok-n">getOrElse</span><span class="tok-o">(</span><span class="tok-s">&quot;begin&quot;</span><span class="tok-o">,</span> <span class="tok-kc">null</span><span class="tok-o">).</span><span class="tok-n">iterator</span><span class="tok-o">.</span><span class="tok-n">next</span><span class="tok-o">()</span>
        <span class="tok-k">val</span> <span class="tok-n">second</span> <span class="tok-k">=</span> <span class="tok-n">pattern</span><span class="tok-o">.</span><span class="tok-n">getOrElse</span><span class="tok-o">(</span><span class="tok-s">&quot;next&quot;</span><span class="tok-o">,</span> <span class="tok-kc">null</span><span class="tok-o">).</span><span class="tok-n">iterator</span><span class="tok-o">.</span><span class="tok-n">next</span><span class="tok-o">()</span>

        <span class="tok-o">(</span><span class="tok-n">second</span><span class="tok-o">.</span><span class="tok-n">userId</span><span class="tok-o">,</span> <span class="tok-n">second</span><span class="tok-o">.</span><span class="tok-n">ip</span><span class="tok-o">,</span> <span class="tok-n">second</span><span class="tok-o">.</span><span class="tok-n">eventType</span><span class="tok-o">)</span>
      <span class="tok-o">})</span>

    <span class="tok-n">loginFailDataStream</span><span class="tok-o">.</span><span class="tok-n">print</span>

    <span class="tok-n">env</span><span class="tok-o">.</span><span class="tok-n">execute</span>
  <span class="tok-o">}</span>

<span class="tok-o">}</span>

<span class="tok-k">case</span> <span class="tok-k">class</span> <span class="tok-nc">LoginEvent</span><span class="tok-o">(</span><span class="tok-n">userId</span><span class="tok-k">:</span> <span class="tok-kt">String</span><span class="tok-o">,</span> <span class="tok-n">ip</span><span class="tok-k">:</span> <span class="tok-kt">String</span><span class="tok-o">,</span> <span class="tok-n">eventType</span><span class="tok-k">:</span> <span class="tok-kt">String</span><span class="tok-o">,</span> <span class="tok-n">eventTime</span><span class="tok-k">:</span> <span class="tok-kt">String</span><span class="tok-o">)</span></code></pre>
</div>
</div>
</div>
</div>
<div class="sect1">
<h2 id="_flink_table_api_sql">11. Flink Table API &amp; SQL</h2>
<div class="sectionbody">
<div class="paragraph">
<p>Table API是流处理和批处理通用的关系型API，Table API可以基于流输入或者批输入来运行而不需要进行任何修改。Table API是SQL语言的超集并专门为Apache Flink设计的，Table API是Scala 和Java语言集成式的API。与常规SQL语言中将查询指定为字符串不同，Table API查询是以Java或Scala中的语言嵌入样式来定义的，具有IDE支持如:自动完成和语法检测。</p>
</div>
<div class="sect2">
<h3 id="_导入依赖">11.1. 导入依赖</h3>
<div class="paragraph">
<p>根据使用的语言不同（Java，Scala），以下依赖选择一个使用。</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="pygments highlight"><code data-lang="xml"><span></span><span class="tok-c">&lt;!-- Either... --&gt;</span>
<span class="tok-nt">&lt;dependency&gt;</span>
  <span class="tok-nt">&lt;groupId&gt;</span>org.apache.flink<span class="tok-nt">&lt;/groupId&gt;</span>
  <span class="tok-nt">&lt;artifactId&gt;</span>flink-table-api-java-bridge_2.11<span class="tok-nt">&lt;/artifactId&gt;</span>
  <span class="tok-nt">&lt;version&gt;</span>1.10.0<span class="tok-nt">&lt;/version&gt;</span>
  <span class="tok-nt">&lt;scope&gt;</span>provided<span class="tok-nt">&lt;/scope&gt;</span>
<span class="tok-nt">&lt;/dependency&gt;</span>
<span class="tok-c">&lt;!-- or... --&gt;</span>
<span class="tok-nt">&lt;dependency&gt;</span>
  <span class="tok-nt">&lt;groupId&gt;</span>org.apache.flink<span class="tok-nt">&lt;/groupId&gt;</span>
  <span class="tok-nt">&lt;artifactId&gt;</span>flink-table-api-scala-bridge_2.11<span class="tok-nt">&lt;/artifactId&gt;</span>
  <span class="tok-nt">&lt;version&gt;</span>1.10.0<span class="tok-nt">&lt;/version&gt;</span>
  <span class="tok-nt">&lt;scope&gt;</span>provided<span class="tok-nt">&lt;/scope&gt;</span>
<span class="tok-nt">&lt;/dependency&gt;</span></code></pre>
</div>
</div>
<div class="paragraph">
<p>如果想兼容以前写的代码，可以使用下面的第一个依赖；如果想要使用阿里巴巴开发的一些新特性（TopN之类的），可以选择第二个依赖。</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="pygments highlight"><code data-lang="xml"><span></span><span class="tok-c">&lt;!-- Either... (for the old planner that was available before Flink 1.9) --&gt;</span>
<span class="tok-nt">&lt;dependency&gt;</span>
  <span class="tok-nt">&lt;groupId&gt;</span>org.apache.flink<span class="tok-nt">&lt;/groupId&gt;</span>
  <span class="tok-nt">&lt;artifactId&gt;</span>flink-table-planner_2.11<span class="tok-nt">&lt;/artifactId&gt;</span>
  <span class="tok-nt">&lt;version&gt;</span>1.10.0<span class="tok-nt">&lt;/version&gt;</span>
  <span class="tok-nt">&lt;scope&gt;</span>provided<span class="tok-nt">&lt;/scope&gt;</span>
<span class="tok-nt">&lt;/dependency&gt;</span>
<span class="tok-c">&lt;!-- or.. (for the new Blink planner) --&gt;</span>
<span class="tok-nt">&lt;dependency&gt;</span>
  <span class="tok-nt">&lt;groupId&gt;</span>org.apache.flink<span class="tok-nt">&lt;/groupId&gt;</span>
  <span class="tok-nt">&lt;artifactId&gt;</span>flink-table-planner-blink_2.11<span class="tok-nt">&lt;/artifactId&gt;</span>
  <span class="tok-nt">&lt;version&gt;</span>1.10.0<span class="tok-nt">&lt;/version&gt;</span>
  <span class="tok-nt">&lt;scope&gt;</span>provided<span class="tok-nt">&lt;/scope&gt;</span>
<span class="tok-nt">&lt;/dependency&gt;</span></code></pre>
</div>
</div>
<div class="paragraph">
<p>如果想要实现一些用户自定义函数（UDF），添加下面的依赖</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="pygments highlight"><code data-lang="xml"><span></span><span class="tok-nt">&lt;dependency&gt;</span>
  <span class="tok-nt">&lt;groupId&gt;</span>org.apache.flink<span class="tok-nt">&lt;/groupId&gt;</span>
  <span class="tok-nt">&lt;artifactId&gt;</span>flink-table-common<span class="tok-nt">&lt;/artifactId&gt;</span>
  <span class="tok-nt">&lt;version&gt;</span>1.10.0<span class="tok-nt">&lt;/version&gt;</span>
  <span class="tok-nt">&lt;scope&gt;</span>provided<span class="tok-nt">&lt;/scope&gt;</span>
<span class="tok-nt">&lt;/dependency&gt;</span></code></pre>
</div>
</div>
</div>
<div class="sect2">
<h3 id="_简单了解table_api">11.2. 简单了解Table API</h3>
<div class="listingblock">
<div class="content">
<pre class="pygments highlight"><code data-lang="scala"><span></span><span class="tok-k">def</span> <span class="tok-n">main</span><span class="tok-o">(</span><span class="tok-n">args</span><span class="tok-k">:</span> <span class="tok-kt">Array</span><span class="tok-o">[</span><span class="tok-kt">String</span><span class="tok-o">])</span><span class="tok-k">:</span> <span class="tok-kt">Unit</span> <span class="tok-o">=</span> <span class="tok-o">{</span>
  <span class="tok-k">val</span> <span class="tok-n">env</span> <span class="tok-k">=</span> <span class="tok-nc">StreamExecutionEnvironment</span><span class="tok-o">.</span><span class="tok-n">getExecutionEnvironment</span>
  <span class="tok-n">env</span><span class="tok-o">.</span><span class="tok-n">setParallelism</span><span class="tok-o">(</span><span class="tok-mi">1</span><span class="tok-o">)</span>
  <span class="tok-k">val</span> <span class="tok-n">inputStream</span> <span class="tok-k">=</span> <span class="tok-n">env</span><span class="tok-o">.</span><span class="tok-n">readTextFile</span><span class="tok-o">(</span><span class="tok-s">&quot;sensor.txt&quot;</span><span class="tok-o">)</span>
  <span class="tok-k">val</span> <span class="tok-n">dataStream</span> <span class="tok-k">=</span> <span class="tok-n">inputStream</span>
    <span class="tok-o">.</span><span class="tok-n">map</span><span class="tok-o">(</span><span class="tok-n">data</span> <span class="tok-k">=&gt;</span> <span class="tok-o">{</span>
      <span class="tok-k">val</span> <span class="tok-n">dataArray</span> <span class="tok-k">=</span> <span class="tok-n">data</span><span class="tok-o">.</span><span class="tok-n">split</span><span class="tok-o">(</span><span class="tok-s">&quot;,&quot;</span><span class="tok-o">)</span>
      <span class="tok-nc">SensorReading</span><span class="tok-o">(</span><span class="tok-n">dataArray</span><span class="tok-o">(</span><span class="tok-mi">0</span><span class="tok-o">).</span><span class="tok-n">trim</span><span class="tok-o">,</span> <span class="tok-n">dataArray</span><span class="tok-o">(</span><span class="tok-mi">1</span><span class="tok-o">).</span><span class="tok-n">trim</span><span class="tok-o">.</span><span class="tok-n">toLong</span><span class="tok-o">,</span> <span class="tok-n">dataArray</span><span class="tok-o">(</span><span class="tok-mi">2</span><span class="tok-o">).</span><span class="tok-n">trim</span><span class="tok-o">.</span><span class="tok-n">toDouble</span><span class="tok-o">)</span>
    <span class="tok-o">})</span>
  <span class="tok-k">val</span> <span class="tok-n">settings</span><span class="tok-k">:</span> <span class="tok-kt">EnvironmentSettings</span> <span class="tok-o">=</span> <span class="tok-nc">EnvironmentSettings</span>
    <span class="tok-o">.</span><span class="tok-n">newInstance</span><span class="tok-o">()</span>
    <span class="tok-o">.</span><span class="tok-n">useOldPlanner</span><span class="tok-o">()</span>
    <span class="tok-o">.</span><span class="tok-n">inStreamingMode</span><span class="tok-o">()</span>
    <span class="tok-o">.</span><span class="tok-n">build</span><span class="tok-o">()</span>
  <span class="tok-k">val</span> <span class="tok-n">tableEnv</span><span class="tok-k">:</span> <span class="tok-kt">StreamTableEnvironment</span> <span class="tok-o">=</span> <span class="tok-nc">StreamTableEnvironment</span><span class="tok-o">.</span><span class="tok-n">create</span><span class="tok-o">(</span><span class="tok-n">env</span><span class="tok-o">,</span> <span class="tok-n">settings</span><span class="tok-o">)</span>
  <span class="tok-c1">// 从一条流创建一张表</span>
  <span class="tok-k">val</span> <span class="tok-n">dataTable</span><span class="tok-k">:</span> <span class="tok-kt">Table</span> <span class="tok-o">=</span> <span class="tok-n">tableEnv</span><span class="tok-o">.</span><span class="tok-n">fromDataStream</span><span class="tok-o">(</span><span class="tok-n">dataStream</span><span class="tok-o">)</span>
  <span class="tok-c1">// 从表里选取特定的数据</span>
  <span class="tok-k">val</span> <span class="tok-n">selectedTable</span><span class="tok-k">:</span> <span class="tok-kt">Table</span> <span class="tok-o">=</span> <span class="tok-n">dataTable</span>
    <span class="tok-o">.</span><span class="tok-n">select</span><span class="tok-o">(</span><span class=" tok--Symbol">&#39;id</span><span class="tok-o">,</span> <span class=" tok--Symbol">&#39;temperature</span><span class="tok-o">)</span>
    <span class="tok-o">.</span><span class="tok-n">filter</span><span class="tok-o">(</span><span class="tok-s">&quot;id = &#39;sensor_1&#39;&quot;</span><span class="tok-o">)</span>
  <span class="tok-k">val</span> <span class="tok-n">selectedStream</span><span class="tok-k">:</span> <span class="tok-kt">DataStream</span><span class="tok-o">[(</span><span class="tok-kt">String</span>, <span class="tok-kt">Double</span><span class="tok-o">)]</span> <span class="tok-k">=</span> <span class="tok-n">selectedTable</span>
    <span class="tok-o">.</span><span class="tok-n">toAppendStream</span><span class="tok-o">[(</span><span class="tok-kt">String</span>, <span class="tok-kt">Double</span><span class="tok-o">)]</span>
  <span class="tok-n">selectedStream</span><span class="tok-o">.</span><span class="tok-n">print</span><span class="tok-o">()</span>
  <span class="tok-n">env</span><span class="tok-o">.</span><span class="tok-n">execute</span><span class="tok-o">(</span><span class="tok-s">&quot;table test&quot;</span><span class="tok-o">)</span>
<span class="tok-o">}</span></code></pre>
</div>
</div>
<div class="sect3">
<h4 id="_动态表">11.2.1. 动态表</h4>
<div class="paragraph">
<p>如果流中的数据类型是case class可以直接根据case class的结构生成table</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="pygments highlight"><code data-lang="scala"><span></span><span class="tok-n">tableEnv</span><span class="tok-o">.</span><span class="tok-n">fromDataStream</span><span class="tok-o">(</span><span class="tok-n">dataStream</span><span class="tok-o">)</span></code></pre>
</div>
</div>
<div class="paragraph">
<p>或者根据字段顺序单独命名</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="pygments highlight"><code data-lang="scala"><span></span><span class="tok-n">tableEnv</span><span class="tok-o">.</span><span class="tok-n">fromDataStream</span><span class="tok-o">(</span><span class="tok-n">dataStream</span><span class="tok-o">,</span> <span class=" tok--Symbol">&#39;id</span><span class="tok-o">,</span> <span class=" tok--Symbol">&#39;timestamp</span><span class="tok-o">)</span></code></pre>
</div>
</div>
<div class="paragraph">
<p>最后的动态表可以转换为流进行输出</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="pygments highlight"><code data-lang="scala"><span></span><span class="tok-n">table</span><span class="tok-o">.</span><span class="tok-n">toAppendStream</span><span class="tok-o">[(</span><span class="tok-kt">String</span>,<span class="tok-kt">String</span><span class="tok-o">)]</span></code></pre>
</div>
</div>
</div>
<div class="sect3">
<h4 id="_字段">11.2.2. 字段</h4>
<div class="paragraph">
<p>用一个单引号放到字段前面来标识字段名, 如 'name , 'id , 'amount 等</p>
</div>
</div>
</div>
<div class="sect2">
<h3 id="_table_api_的窗口聚合操作">11.3. Table API 的窗口聚合操作</h3>
<div class="sect3">
<h4 id="_通过一个例子了解tableapi">11.3.1. 通过一个例子了解TableAPI</h4>
<div class="listingblock">
<div class="content">
<pre class="pygments highlight"><code data-lang="scala"><span></span><span class="tok-c1">// 统计每10秒中每个传感器温度值的个数</span>
<span class="tok-k">def</span> <span class="tok-n">main</span><span class="tok-o">(</span><span class="tok-n">args</span><span class="tok-k">:</span> <span class="tok-kt">Array</span><span class="tok-o">[</span><span class="tok-kt">String</span><span class="tok-o">])</span><span class="tok-k">:</span> <span class="tok-kt">Unit</span> <span class="tok-o">=</span> <span class="tok-o">{</span>
  <span class="tok-k">val</span> <span class="tok-n">env</span> <span class="tok-k">=</span> <span class="tok-nc">StreamExecutionEnvironment</span><span class="tok-o">.</span><span class="tok-n">getExecutionEnvironment</span>
  <span class="tok-n">env</span><span class="tok-o">.</span><span class="tok-n">setParallelism</span><span class="tok-o">(</span><span class="tok-mi">1</span><span class="tok-o">)</span>
  <span class="tok-n">env</span><span class="tok-o">.</span><span class="tok-n">setStreamTimeCharacteristic</span><span class="tok-o">(</span><span class="tok-nc">TimeCharacteristic</span><span class="tok-o">.</span><span class="tok-nc">EventTime</span><span class="tok-o">)</span>
  <span class="tok-k">val</span> <span class="tok-n">inputStream</span> <span class="tok-k">=</span> <span class="tok-n">env</span><span class="tok-o">.</span><span class="tok-n">readTextFile</span><span class="tok-o">(</span><span class="tok-s">&quot;..\\sensor.txt&quot;</span><span class="tok-o">)</span>
  <span class="tok-k">val</span> <span class="tok-n">dataStream</span> <span class="tok-k">=</span> <span class="tok-n">inputStream</span>
    <span class="tok-o">.</span><span class="tok-n">map</span><span class="tok-o">(</span><span class="tok-n">data</span> <span class="tok-k">=&gt;</span> <span class="tok-o">{</span>
      <span class="tok-k">val</span> <span class="tok-n">dataArray</span> <span class="tok-k">=</span> <span class="tok-n">data</span><span class="tok-o">.</span><span class="tok-n">split</span><span class="tok-o">(</span><span class="tok-s">&quot;,&quot;</span><span class="tok-o">)</span>
      <span class="tok-nc">SensorReading</span><span class="tok-o">(</span><span class="tok-n">dataArray</span><span class="tok-o">(</span><span class="tok-mi">0</span><span class="tok-o">).</span><span class="tok-n">trim</span><span class="tok-o">,</span> <span class="tok-n">dataArray</span><span class="tok-o">(</span><span class="tok-mi">1</span><span class="tok-o">).</span><span class="tok-n">trim</span><span class="tok-o">.</span><span class="tok-n">toLong</span><span class="tok-o">,</span> <span class="tok-n">dataArray</span><span class="tok-o">(</span><span class="tok-mi">2</span><span class="tok-o">).</span><span class="tok-n">trim</span><span class="tok-o">.</span><span class="tok-n">toDouble</span><span class="tok-o">)</span>
    <span class="tok-o">})</span>
    <span class="tok-o">.</span><span class="tok-n">assignTimestampsAndWatermarks</span><span class="tok-o">(</span>
      <span class="tok-k">new</span> <span class="tok-nc">BoundedOutOfOrdernessTimestampExtractor</span><span class="tok-o">[</span><span class="tok-kt">SensorReading</span><span class="tok-o">](</span><span class="tok-nc">Time</span><span class="tok-o">.</span><span class="tok-n">seconds</span><span class="tok-o">(</span><span class="tok-mi">1</span><span class="tok-o">))</span> <span class="tok-o">{</span>
        <span class="tok-k">override</span> <span class="tok-k">def</span> <span class="tok-n">extractTimestamp</span><span class="tok-o">(</span><span class="tok-n">element</span><span class="tok-k">:</span> <span class="tok-kt">SensorReading</span><span class="tok-o">)</span><span class="tok-k">:</span> <span class="tok-kt">Long</span> <span class="tok-o">=</span> <span class="tok-n">element</span><span class="tok-o">.</span><span class="tok-n">timestamp</span> <span class="tok-o">*</span> <span class="tok-mi">1000L</span>
      <span class="tok-o">}</span>
    <span class="tok-o">)</span>
  <span class="tok-c1">// 基于env创建 tableEnv</span>
  <span class="tok-k">val</span> <span class="tok-n">settings</span><span class="tok-k">:</span> <span class="tok-kt">EnvironmentSettings</span> <span class="tok-o">=</span> <span class="tok-nc">EnvironmentSettings</span>
    <span class="tok-o">.</span><span class="tok-n">newInstance</span><span class="tok-o">()</span>
    <span class="tok-o">.</span><span class="tok-n">useOldPlanner</span><span class="tok-o">()</span>
    <span class="tok-o">.</span><span class="tok-n">inStreamingMode</span><span class="tok-o">()</span>
    <span class="tok-o">.</span><span class="tok-n">build</span><span class="tok-o">()</span>
  <span class="tok-k">val</span> <span class="tok-n">tableEnv</span><span class="tok-k">:</span> <span class="tok-kt">StreamTableEnvironment</span> <span class="tok-o">=</span> <span class="tok-nc">StreamTableEnvironment</span><span class="tok-o">.</span><span class="tok-n">create</span><span class="tok-o">(</span><span class="tok-n">env</span><span class="tok-o">,</span> <span class="tok-n">settings</span><span class="tok-o">)</span>
  <span class="tok-c1">// 从一条流创建一张表，按照字段去定义，并指定事件时间的时间字段</span>
  <span class="tok-k">val</span> <span class="tok-n">dataTable</span><span class="tok-k">:</span> <span class="tok-kt">Table</span> <span class="tok-o">=</span> <span class="tok-n">tableEnv</span><span class="tok-o">.</span><span class="tok-n">fromDataStream</span><span class="tok-o">(</span><span class="tok-n">dataStream</span><span class="tok-o">,</span> <span class=" tok--Symbol">&#39;id</span><span class="tok-o">,</span> <span class=" tok--Symbol">&#39;temperature</span><span class="tok-o">,</span> <span class=" tok--Symbol">&#39;ts</span><span class="tok-o">.</span><span class="tok-n">rowtime</span><span class="tok-o">)</span>
  <span class="tok-c1">// 按照时间开窗聚合统计</span>
  <span class="tok-k">val</span> <span class="tok-n">resultTable</span><span class="tok-k">:</span> <span class="tok-kt">Table</span> <span class="tok-o">=</span> <span class="tok-n">dataTable</span>
    <span class="tok-o">.</span><span class="tok-n">window</span><span class="tok-o">(</span><span class="tok-nc">Tumble</span> <span class="tok-n">over</span> <span class="tok-mf">10.</span><span class="tok-n">seconds</span> <span class="tok-n">on</span> <span class=" tok--Symbol">&#39;ts</span> <span class="tok-n">as</span> <span class=" tok--Symbol">&#39;tw</span> <span class="tok-o">)</span>
    <span class="tok-o">.</span><span class="tok-n">groupBy</span><span class="tok-o">(</span><span class=" tok--Symbol">&#39;id</span><span class="tok-o">,</span> <span class=" tok--Symbol">&#39;tw</span><span class="tok-o">)</span>
    <span class="tok-o">.</span><span class="tok-n">select</span><span class="tok-o">(</span><span class=" tok--Symbol">&#39;id</span><span class="tok-o">,</span> <span class=" tok--Symbol">&#39;id</span><span class="tok-o">.</span><span class="tok-n">count</span><span class="tok-o">)</span>
  <span class="tok-k">val</span> <span class="tok-n">selectedStream</span><span class="tok-k">:</span> <span class="tok-kt">DataStream</span><span class="tok-o">[(</span><span class="tok-kt">Boolean</span>, <span class="tok-o">(</span><span class="tok-kt">String</span>, <span class="tok-kt">Long</span><span class="tok-o">))]</span> <span class="tok-k">=</span> <span class="tok-n">resultTable</span>
    <span class="tok-o">.</span><span class="tok-n">toRetractStream</span><span class="tok-o">[(</span><span class="tok-kt">String</span>, <span class="tok-kt">Long</span><span class="tok-o">)]</span>
  <span class="tok-n">selectedStream</span><span class="tok-o">.</span><span class="tok-n">print</span><span class="tok-o">()</span>
  <span class="tok-n">env</span><span class="tok-o">.</span><span class="tok-n">execute</span><span class="tok-o">(</span><span class="tok-s">&quot;table window test&quot;</span><span class="tok-o">)</span>
<span class="tok-o">}</span></code></pre>
</div>
</div>
</div>
<div class="sect3">
<h4 id="_关于group_by">11.3.2. 关于group by</h4>
<div class="olist arabic">
<ol class="arabic" start="1">
<li>
<p>如果使用了 groupby，table转换为流的时候只能用toRetractStream</p>
</li>
</ol>
</div>
<div class="listingblock">
<div class="content">
<pre class="pygments highlight"><code data-lang="scala"><span></span><span class="tok-k">val</span> <span class="tok-n">dataStream</span><span class="tok-k">:</span> <span class="tok-kt">DataStream</span><span class="tok-o">[(</span><span class="tok-kt">Boolean</span>, <span class="tok-o">(</span><span class="tok-kt">String</span>, <span class="tok-kt">Long</span><span class="tok-o">))]</span> <span class="tok-k">=</span> <span class="tok-n">table</span><span class="tok-o">.</span><span class="tok-n">toRetractStream</span><span class="tok-o">[(</span><span class="tok-kt">String</span>,<span class="tok-kt">Long</span><span class="tok-o">)]</span></code></pre>
</div>
</div>
<div class="olist arabic">
<ol class="arabic" start="2">
<li>
<p>toRetractDstream得到的第一个boolean型字段标识true就是最新的数据(Insert)，false表示过期老数据(Delete)</p>
</li>
</ol>
</div>
<div class="listingblock">
<div class="content">
<pre class="pygments highlight"><code data-lang="scala"><span></span><span class="tok-k">val</span> <span class="tok-n">dataStream</span><span class="tok-k">:</span> <span class="tok-kt">DataStream</span><span class="tok-o">[(</span><span class="tok-kt">Boolean</span>, <span class="tok-o">(</span><span class="tok-kt">String</span>, <span class="tok-kt">Long</span><span class="tok-o">))]</span> <span class="tok-k">=</span> <span class="tok-n">table</span><span class="tok-o">.</span><span class="tok-n">toRetractStream</span><span class="tok-o">[(</span><span class="tok-kt">String</span>,<span class="tok-kt">Long</span><span class="tok-o">)]</span>
<span class="tok-n">dataStream</span><span class="tok-o">.</span><span class="tok-n">filter</span><span class="tok-o">(</span><span class="tok-k">_</span><span class="tok-o">.</span><span class="tok-n">_1</span><span class="tok-o">).</span><span class="tok-n">print</span><span class="tok-o">()</span></code></pre>
</div>
</div>
<div class="olist arabic">
<ol class="arabic" start="3">
<li>
<p>如果使用的api包括时间窗口，那么窗口的字段必须出现在groupBy中。</p>
</li>
</ol>
</div>
<div class="listingblock">
<div class="content">
<pre class="pygments highlight"><code data-lang="scala"><span></span><span class="tok-k">val</span> <span class="tok-n">resultTable</span><span class="tok-k">:</span> <span class="tok-kt">Table</span> <span class="tok-o">=</span> <span class="tok-n">dataTable</span>
  <span class="tok-o">.</span><span class="tok-n">window</span><span class="tok-o">(</span> <span class="tok-nc">Tumble</span> <span class="tok-n">over</span> <span class="tok-mf">10.</span><span class="tok-n">seconds</span> <span class="tok-n">on</span> <span class=" tok--Symbol">&#39;ts</span> <span class="tok-n">as</span> <span class=" tok--Symbol">&#39;tw</span> <span class="tok-o">)</span>
  <span class="tok-o">.</span><span class="tok-n">groupBy</span><span class="tok-o">(</span><span class=" tok--Symbol">&#39;id</span><span class="tok-o">,</span> <span class=" tok--Symbol">&#39;tw</span><span class="tok-o">)</span>
  <span class="tok-o">.</span><span class="tok-n">select</span><span class="tok-o">(</span><span class=" tok--Symbol">&#39;id</span><span class="tok-o">,</span> <span class=" tok--Symbol">&#39;id</span><span class="tok-o">.</span><span class="tok-n">count</span><span class="tok-o">)</span></code></pre>
</div>
</div>
</div>
<div class="sect3">
<h4 id="_关于时间窗口">11.3.3. 关于时间窗口</h4>
<div class="olist arabic">
<ol class="arabic" start="1">
<li>
<p>用到时间窗口，必须提前声明时间字段，如果是Processing Time直接在创建动态表时进行追加就可以。</p>
</li>
</ol>
</div>
<div class="listingblock">
<div class="content">
<pre class="pygments highlight"><code data-lang="scala"><span></span><span class="tok-k">val</span> <span class="tok-n">dataTable</span><span class="tok-k">:</span> <span class="tok-kt">Table</span> <span class="tok-o">=</span> <span class="tok-n">tableEnv</span><span class="tok-o">.</span><span class="tok-n">fromDataStream</span><span class="tok-o">(</span><span class="tok-n">dataStream</span><span class="tok-o">,</span> <span class=" tok--Symbol">&#39;id</span><span class="tok-o">,</span> <span class=" tok--Symbol">&#39;temperature</span><span class="tok-o">,</span> <span class=" tok--Symbol">&#39;ps</span><span class="tok-o">.</span><span class="tok-n">proctime</span><span class="tok-o">)</span></code></pre>
</div>
</div>
<div class="olist arabic">
<ol class="arabic" start="2">
<li>
<p>如果是EventTime要在创建动态表时声明</p>
</li>
</ol>
</div>
<div class="listingblock">
<div class="content">
<pre class="pygments highlight"><code data-lang="scala"><span></span><span class="tok-k">val</span> <span class="tok-n">dataTable</span><span class="tok-k">:</span> <span class="tok-kt">Table</span> <span class="tok-o">=</span> <span class="tok-n">tableEnv</span><span class="tok-o">.</span><span class="tok-n">fromDataStream</span><span class="tok-o">(</span><span class="tok-n">dataStream</span><span class="tok-o">,</span> <span class=" tok--Symbol">&#39;id</span><span class="tok-o">,</span> <span class=" tok--Symbol">&#39;temperature</span><span class="tok-o">,</span> <span class=" tok--Symbol">&#39;ts</span><span class="tok-o">.</span><span class="tok-n">rowtime</span><span class="tok-o">)</span></code></pre>
</div>
</div>
<div class="olist arabic">
<ol class="arabic" start="3">
<li>
<p>滚动窗口可以使用Tumble over 10000.millis on来表示</p>
</li>
</ol>
</div>
<div class="listingblock">
<div class="content">
<pre class="pygments highlight"><code data-lang="scala"><span></span><span class="tok-k">val</span> <span class="tok-n">resultTable</span><span class="tok-k">:</span> <span class="tok-kt">Table</span> <span class="tok-o">=</span> <span class="tok-n">dataTable</span>
  <span class="tok-o">.</span><span class="tok-n">window</span><span class="tok-o">(</span> <span class="tok-nc">Tumble</span> <span class="tok-n">over</span> <span class="tok-mf">10.</span><span class="tok-n">seconds</span> <span class="tok-n">on</span> <span class=" tok--Symbol">&#39;ts</span> <span class="tok-n">as</span> <span class=" tok--Symbol">&#39;tw</span><span class="tok-o">)</span>
  <span class="tok-o">.</span><span class="tok-n">groupBy</span><span class="tok-o">(</span><span class=" tok--Symbol">&#39;id</span><span class="tok-o">,</span> <span class=" tok--Symbol">&#39;tw</span><span class="tok-o">)</span>
  <span class="tok-o">.</span><span class="tok-n">select</span><span class="tok-o">(</span><span class=" tok--Symbol">&#39;id</span><span class="tok-o">,</span> <span class=" tok--Symbol">&#39;id</span><span class="tok-o">.</span><span class="tok-n">count</span><span class="tok-o">)</span></code></pre>
</div>
</div>
</div>
</div>
<div class="sect2">
<h3 id="_sql如何编写">11.4. SQL如何编写</h3>
<div class="listingblock">
<div class="content">
<pre class="pygments highlight"><code data-lang="scala"><span></span><span class="tok-c1">// 统计每10秒中每个传感器温度值的个数</span>
<span class="tok-k">def</span> <span class="tok-n">main</span><span class="tok-o">(</span><span class="tok-n">args</span><span class="tok-k">:</span> <span class="tok-kt">Array</span><span class="tok-o">[</span><span class="tok-kt">String</span><span class="tok-o">])</span><span class="tok-k">:</span> <span class="tok-kt">Unit</span> <span class="tok-o">=</span> <span class="tok-o">{</span>
  <span class="tok-k">val</span> <span class="tok-n">env</span> <span class="tok-k">=</span> <span class="tok-nc">StreamExecutionEnvironment</span><span class="tok-o">.</span><span class="tok-n">getExecutionEnvironment</span>
  <span class="tok-n">env</span><span class="tok-o">.</span><span class="tok-n">setParallelism</span><span class="tok-o">(</span><span class="tok-mi">1</span><span class="tok-o">)</span>
  <span class="tok-n">env</span><span class="tok-o">.</span><span class="tok-n">setStreamTimeCharacteristic</span><span class="tok-o">(</span><span class="tok-nc">TimeCharacteristic</span><span class="tok-o">.</span><span class="tok-nc">EventTime</span><span class="tok-o">)</span>
  <span class="tok-k">val</span> <span class="tok-n">inputStream</span> <span class="tok-k">=</span> <span class="tok-n">env</span><span class="tok-o">.</span><span class="tok-n">readTextFile</span><span class="tok-o">(</span><span class="tok-s">&quot;sensor.txt&quot;</span><span class="tok-o">)</span>
  <span class="tok-k">val</span> <span class="tok-n">dataStream</span> <span class="tok-k">=</span> <span class="tok-n">inputStream</span>
    <span class="tok-o">.</span><span class="tok-n">map</span><span class="tok-o">(</span><span class="tok-n">data</span> <span class="tok-k">=&gt;</span> <span class="tok-o">{</span>
      <span class="tok-k">val</span> <span class="tok-n">dataArray</span> <span class="tok-k">=</span> <span class="tok-n">data</span><span class="tok-o">.</span><span class="tok-n">split</span><span class="tok-o">(</span><span class="tok-s">&quot;,&quot;</span><span class="tok-o">)</span>
      <span class="tok-nc">SensorReading</span><span class="tok-o">(</span><span class="tok-n">dataArray</span><span class="tok-o">(</span><span class="tok-mi">0</span><span class="tok-o">).</span><span class="tok-n">trim</span><span class="tok-o">,</span> <span class="tok-n">dataArray</span><span class="tok-o">(</span><span class="tok-mi">1</span><span class="tok-o">).</span><span class="tok-n">trim</span><span class="tok-o">.</span><span class="tok-n">toLong</span><span class="tok-o">,</span> <span class="tok-n">dataArray</span><span class="tok-o">(</span><span class="tok-mi">2</span><span class="tok-o">).</span><span class="tok-n">trim</span><span class="tok-o">.</span><span class="tok-n">toDouble</span><span class="tok-o">)</span>
    <span class="tok-o">})</span>
    <span class="tok-o">.</span><span class="tok-n">assignTimestampsAndWatermarks</span><span class="tok-o">(</span>
      <span class="tok-k">new</span> <span class="tok-nc">BoundedOutOfOrdernessTimestampExtractor</span><span class="tok-o">[</span><span class="tok-kt">SensorReading</span><span class="tok-o">](</span><span class="tok-nc">Time</span><span class="tok-o">.</span><span class="tok-n">seconds</span><span class="tok-o">(</span><span class="tok-mi">1</span><span class="tok-o">))</span> <span class="tok-o">{</span>
        <span class="tok-k">override</span> <span class="tok-k">def</span> <span class="tok-n">extractTimestamp</span><span class="tok-o">(</span><span class="tok-n">element</span><span class="tok-k">:</span> <span class="tok-kt">SensorReading</span><span class="tok-o">)</span><span class="tok-k">:</span> <span class="tok-kt">Long</span> <span class="tok-o">=</span> <span class="tok-n">element</span><span class="tok-o">.</span><span class="tok-n">timestamp</span> <span class="tok-o">*</span> <span class="tok-mi">1000L</span>
      <span class="tok-o">}</span>
    <span class="tok-o">)</span>
  <span class="tok-c1">// 基于env创建 tableEnv</span>
  <span class="tok-k">val</span> <span class="tok-n">settings</span><span class="tok-k">:</span> <span class="tok-kt">EnvironmentSettings</span> <span class="tok-o">=</span> <span class="tok-nc">EnvironmentSettings</span>
    <span class="tok-o">.</span><span class="tok-n">newInstance</span><span class="tok-o">()</span>
    <span class="tok-o">.</span><span class="tok-n">useOldPlanner</span><span class="tok-o">()</span>
    <span class="tok-o">.</span><span class="tok-n">inStreamingMode</span><span class="tok-o">()</span>
    <span class="tok-o">.</span><span class="tok-n">build</span><span class="tok-o">()</span>
  <span class="tok-k">val</span> <span class="tok-n">tableEnv</span><span class="tok-k">:</span> <span class="tok-kt">StreamTableEnvironment</span> <span class="tok-o">=</span> <span class="tok-nc">StreamTableEnvironment</span><span class="tok-o">.</span><span class="tok-n">create</span><span class="tok-o">(</span><span class="tok-n">env</span><span class="tok-o">,</span> <span class="tok-n">settings</span><span class="tok-o">)</span>
  <span class="tok-c1">// 从一条流创建一张表，按照字段去定义，并指定事件时间的时间字段</span>
  <span class="tok-k">val</span> <span class="tok-n">dataTable</span><span class="tok-k">:</span> <span class="tok-kt">Table</span> <span class="tok-o">=</span> <span class="tok-n">tableEnv</span><span class="tok-o">.</span><span class="tok-n">fromDataStream</span><span class="tok-o">(</span><span class="tok-n">dataStream</span><span class="tok-o">,</span> <span class=" tok--Symbol">&#39;id</span><span class="tok-o">,</span> <span class=" tok--Symbol">&#39;temperature</span><span class="tok-o">,</span> <span class=" tok--Symbol">&#39;ts</span><span class="tok-o">.</span><span class="tok-n">rowtime</span><span class="tok-o">)</span>
  <span class="tok-c1">// 直接写sql完成开窗统计</span>
  <span class="tok-k">val</span> <span class="tok-n">resultSqlTable</span><span class="tok-k">:</span> <span class="tok-kt">Table</span> <span class="tok-o">=</span> <span class="tok-n">tableEnv</span><span class="tok-o">.</span><span class="tok-n">sqlQuery</span><span class="tok-o">(</span><span class="tok-s">&quot;select id, count(id) from &quot;</span> <span class="tok-o">+</span> <span class="tok-n">dataTable</span> <span class="tok-o">+</span> <span class="tok-s">&quot; group by id, tumble(ts, interval &#39;15&#39; second)&quot;</span><span class="tok-o">)</span>
  <span class="tok-k">val</span> <span class="tok-n">selectedStream</span><span class="tok-k">:</span> <span class="tok-kt">DataStream</span><span class="tok-o">[(</span><span class="tok-kt">Boolean</span>, <span class="tok-o">(</span><span class="tok-kt">String</span>, <span class="tok-kt">Long</span><span class="tok-o">))]</span> <span class="tok-k">=</span> <span class="tok-n">resultSqlTable</span><span class="tok-o">.</span><span class="tok-n">toRetractStream</span><span class="tok-o">[(</span><span class="tok-kt">String</span>, <span class="tok-kt">Long</span><span class="tok-o">)]</span>
  <span class="tok-n">selectedStream</span><span class="tok-o">.</span><span class="tok-n">print</span><span class="tok-o">()</span>
  <span class="tok-n">env</span><span class="tok-o">.</span><span class="tok-n">execute</span><span class="tok-o">(</span><span class="tok-s">&quot;table window test&quot;</span><span class="tok-o">)</span>
<span class="tok-o">}</span></code></pre>
</div>
</div>
</div>
<div class="sect2">
<h3 id="_使用table_api结合sql实现topn需求">11.5. 使用Table API结合SQL实现TopN需求</h3>
<div class="listingblock">
<div class="content">
<pre class="pygments highlight"><code data-lang="scala"><span></span><span class="tok-k">package</span> <span class="tok-nn">com.atguigu.project.topnhotitems</span>

<span class="tok-k">import</span> <span class="tok-nn">java.sql.Timestamp</span>

<span class="tok-k">import</span> <span class="tok-nn">com.atguigu.project.util.UserBehavior</span>
<span class="tok-k">import</span> <span class="tok-nn">org.apache.flink.streaming.api.TimeCharacteristic</span>
<span class="tok-k">import</span> <span class="tok-nn">org.apache.flink.streaming.api.scala.StreamExecutionEnvironment</span>
<span class="tok-k">import</span> <span class="tok-nn">org.apache.flink.api.scala._</span>
<span class="tok-k">import</span> <span class="tok-nn">org.apache.flink.table.api.</span><span class="tok-o">{</span><span class="tok-nc">EnvironmentSettings</span><span class="tok-o">,</span> <span class="tok-nc">Tumble</span><span class="tok-o">}</span>
<span class="tok-k">import</span> <span class="tok-nn">org.apache.flink.table.api.scala._</span>

<span class="tok-k">object</span> <span class="tok-nc">HotItemsTable</span> <span class="tok-o">{</span>

  <span class="tok-k">def</span> <span class="tok-n">main</span><span class="tok-o">(</span><span class="tok-n">args</span><span class="tok-k">:</span> <span class="tok-kt">Array</span><span class="tok-o">[</span><span class="tok-kt">String</span><span class="tok-o">])</span><span class="tok-k">:</span> <span class="tok-kt">Unit</span> <span class="tok-o">=</span> <span class="tok-o">{</span>

    <span class="tok-k">val</span> <span class="tok-n">env</span> <span class="tok-k">=</span> <span class="tok-nc">StreamExecutionEnvironment</span><span class="tok-o">.</span><span class="tok-n">getExecutionEnvironment</span>
    <span class="tok-c1">// 有关Blink的配置，样板代码</span>
    <span class="tok-k">val</span> <span class="tok-n">settings</span> <span class="tok-k">=</span> <span class="tok-nc">EnvironmentSettings</span><span class="tok-o">.</span><span class="tok-n">newInstance</span><span class="tok-o">()</span>
      <span class="tok-o">.</span><span class="tok-n">useBlinkPlanner</span><span class="tok-o">()</span>
      <span class="tok-o">.</span><span class="tok-n">inStreamingMode</span><span class="tok-o">()</span>
      <span class="tok-o">.</span><span class="tok-n">build</span><span class="tok-o">()</span>
    <span class="tok-c1">// 创建流式表的环境</span>
    <span class="tok-k">val</span> <span class="tok-n">tEnv</span> <span class="tok-k">=</span> <span class="tok-nc">StreamTableEnvironment</span><span class="tok-o">.</span><span class="tok-n">create</span><span class="tok-o">(</span><span class="tok-n">env</span><span class="tok-o">,</span> <span class="tok-n">settings</span><span class="tok-o">)</span>
    <span class="tok-n">env</span><span class="tok-o">.</span><span class="tok-n">setParallelism</span><span class="tok-o">(</span><span class="tok-mi">1</span><span class="tok-o">)</span>
    <span class="tok-c1">// 使用事件时间</span>
    <span class="tok-n">env</span><span class="tok-o">.</span><span class="tok-n">setStreamTimeCharacteristic</span><span class="tok-o">(</span><span class="tok-nc">TimeCharacteristic</span><span class="tok-o">.</span><span class="tok-nc">EventTime</span><span class="tok-o">)</span>
    <span class="tok-c1">// 过滤出pv事件，并抽取时间戳</span>
    <span class="tok-k">val</span> <span class="tok-n">stream</span> <span class="tok-k">=</span> <span class="tok-n">env</span>
      <span class="tok-o">.</span><span class="tok-n">readTextFile</span><span class="tok-o">(</span><span class="tok-s">&quot;/home/parallels/flink-tutorial/Flink0830Tutorial/src/main/resources/UserBehavior.csv&quot;</span><span class="tok-o">)</span>
      <span class="tok-o">.</span><span class="tok-n">map</span><span class="tok-o">(</span><span class="tok-n">line</span> <span class="tok-k">=&gt;</span> <span class="tok-o">{</span>
        <span class="tok-k">val</span> <span class="tok-n">arr</span> <span class="tok-k">=</span> <span class="tok-n">line</span><span class="tok-o">.</span><span class="tok-n">split</span><span class="tok-o">(</span><span class="tok-s">&quot;,&quot;</span><span class="tok-o">)</span>
        <span class="tok-nc">UserBehavior</span><span class="tok-o">(</span><span class="tok-n">arr</span><span class="tok-o">(</span><span class="tok-mi">0</span><span class="tok-o">).</span><span class="tok-n">toLong</span><span class="tok-o">,</span> <span class="tok-n">arr</span><span class="tok-o">(</span><span class="tok-mi">1</span><span class="tok-o">).</span><span class="tok-n">toLong</span><span class="tok-o">,</span> <span class="tok-n">arr</span><span class="tok-o">(</span><span class="tok-mi">2</span><span class="tok-o">).</span><span class="tok-n">toInt</span><span class="tok-o">,</span> <span class="tok-n">arr</span><span class="tok-o">(</span><span class="tok-mi">3</span><span class="tok-o">),</span> <span class="tok-n">arr</span><span class="tok-o">(</span><span class="tok-mi">4</span><span class="tok-o">).</span><span class="tok-n">toLong</span> <span class="tok-o">*</span> <span class="tok-mi">1000</span><span class="tok-o">)</span>
      <span class="tok-o">})</span>
      <span class="tok-o">.</span><span class="tok-n">filter</span><span class="tok-o">(</span><span class="tok-k">_</span><span class="tok-o">.</span><span class="tok-n">behavior</span> <span class="tok-o">==</span> <span class="tok-s">&quot;pv&quot;</span><span class="tok-o">)</span>
      <span class="tok-o">.</span><span class="tok-n">assignAscendingTimestamps</span><span class="tok-o">(</span><span class="tok-k">_</span><span class="tok-o">.</span><span class="tok-n">timestamp</span><span class="tok-o">)</span>

    <span class="tok-c1">// 从流中提取两个字段，时间戳；itemId，组成一张表</span>
    <span class="tok-k">val</span> <span class="tok-n">table</span> <span class="tok-k">=</span> <span class="tok-n">tEnv</span><span class="tok-o">.</span><span class="tok-n">fromDataStream</span><span class="tok-o">(</span><span class="tok-n">stream</span><span class="tok-o">,</span> <span class=" tok--Symbol">&#39;timestamp</span><span class="tok-o">.</span><span class="tok-n">rowtime</span><span class="tok-o">,</span> <span class=" tok--Symbol">&#39;itemId</span><span class="tok-o">)</span>
    <span class="tok-k">val</span> <span class="tok-n">t</span> <span class="tok-k">=</span> <span class="tok-n">table</span>
      <span class="tok-o">.</span><span class="tok-n">window</span><span class="tok-o">(</span><span class="tok-nc">Tumble</span> <span class="tok-n">over</span> <span class="tok-mf">60.</span><span class="tok-n">minutes</span> <span class="tok-n">on</span> <span class=" tok--Symbol">&#39;timestamp</span> <span class="tok-n">as</span> <span class=" tok--Symbol">&#39;w</span><span class="tok-o">)</span> <span class="tok-c1">// 一小时滚动窗口</span>
      <span class="tok-o">.</span><span class="tok-n">groupBy</span><span class="tok-o">(</span><span class=" tok--Symbol">&#39;itemId</span><span class="tok-o">,</span> <span class=" tok--Symbol">&#39;w</span><span class="tok-o">)</span>                               <span class="tok-c1">// 根据itemId和窗口进行分组</span>
      <span class="tok-o">.</span><span class="tok-n">aggregate</span><span class="tok-o">(</span><span class=" tok--Symbol">&#39;itemId</span><span class="tok-o">.</span><span class="tok-n">count</span> <span class="tok-n">as</span> <span class=" tok--Symbol">&#39;icount</span><span class="tok-o">)</span>                <span class="tok-c1">// 对itemId进行计数</span>
      <span class="tok-o">.</span><span class="tok-n">select</span><span class="tok-o">(</span><span class=" tok--Symbol">&#39;itemId</span><span class="tok-o">,</span> <span class=" tok--Symbol">&#39;icount</span><span class="tok-o">,</span> <span class=" tok--Symbol">&#39;w</span><span class="tok-o">.</span><span class="tok-n">end</span> <span class="tok-n">as</span> <span class=" tok--Symbol">&#39;windowEnd</span><span class="tok-o">)</span>     <span class="tok-c1">// 查询三个字段</span>
      <span class="tok-o">.</span><span class="tok-n">toAppendStream</span><span class="tok-o">[(</span><span class="tok-kt">Long</span>, <span class="tok-kt">Long</span>, <span class="tok-kt">Timestamp</span><span class="tok-o">)]</span>            <span class="tok-c1">// 转换成DataStream</span>

    <span class="tok-c1">// 创建临时表</span>
    <span class="tok-n">tEnv</span><span class="tok-o">.</span><span class="tok-n">createTemporaryView</span><span class="tok-o">(</span><span class="tok-s">&quot;topn&quot;</span><span class="tok-o">,</span> <span class="tok-n">t</span><span class="tok-o">,</span> <span class=" tok--Symbol">&#39;itemId</span><span class="tok-o">,</span> <span class=" tok--Symbol">&#39;icount</span><span class="tok-o">,</span> <span class=" tok--Symbol">&#39;windowEnd</span><span class="tok-o">)</span>

    <span class="tok-c1">// topN查询，Blink支持的特性</span>
    <span class="tok-k">val</span> <span class="tok-n">result</span> <span class="tok-k">=</span> <span class="tok-n">tEnv</span><span class="tok-o">.</span><span class="tok-n">sqlQuery</span><span class="tok-o">(</span>
      <span class="tok-s">&quot;&quot;&quot;</span>
<span class="tok-s">        |SELECT *</span>
<span class="tok-s">        |FROM (</span>
<span class="tok-s">        |    SELECT *,</span>
<span class="tok-s">        |        ROW_NUMBER() OVER (PARTITION BY windowEnd ORDER BY icount DESC) as row_num</span>
<span class="tok-s">        |    FROM topn)</span>
<span class="tok-s">        |WHERE row_num &lt;= 5</span>
<span class="tok-s">        |&quot;&quot;&quot;</span><span class="tok-o">.</span><span class="tok-n">stripMargin</span>
    <span class="tok-o">)</span>
    <span class="tok-c1">// 使用toRetractStream转换成DataStream，用来实时更新排行榜</span>
    <span class="tok-c1">// true代表insert, false代表delete</span>
    <span class="tok-n">result</span><span class="tok-o">.</span><span class="tok-n">toRetractStream</span><span class="tok-o">[(</span><span class="tok-kt">Long</span>, <span class="tok-kt">Long</span>, <span class="tok-kt">Timestamp</span>, <span class="tok-kt">Long</span><span class="tok-o">)].</span><span class="tok-n">print</span><span class="tok-o">()</span>

    <span class="tok-n">env</span><span class="tok-o">.</span><span class="tok-n">execute</span><span class="tok-o">()</span>
  <span class="tok-o">}</span>
<span class="tok-o">}</span></code></pre>
</div>
</div>
</div>
<div class="sect2">
<h3 id="_只使用flink_sql实现topn需求">11.6. 只使用Flink SQL实现TopN需求</h3>
<div class="paragraph">
<p>代码</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="pygments highlight"><code data-lang="scala"><span></span><span class="tok-k">package</span> <span class="tok-nn">com.atguigu.project.topnhotitems</span>

<span class="tok-k">import</span> <span class="tok-nn">java.sql.Timestamp</span>

<span class="tok-k">import</span> <span class="tok-nn">com.atguigu.project.util.UserBehavior</span>
<span class="tok-k">import</span> <span class="tok-nn">org.apache.flink.streaming.api.TimeCharacteristic</span>
<span class="tok-k">import</span> <span class="tok-nn">org.apache.flink.streaming.api.scala.StreamExecutionEnvironment</span>
<span class="tok-k">import</span> <span class="tok-nn">org.apache.flink.api.scala._</span>
<span class="tok-k">import</span> <span class="tok-nn">org.apache.flink.table.api.</span><span class="tok-o">{</span><span class="tok-nc">EnvironmentSettings</span><span class="tok-o">,</span> <span class="tok-nc">Tumble</span><span class="tok-o">}</span>
<span class="tok-k">import</span> <span class="tok-nn">org.apache.flink.table.api.scala._</span>

<span class="tok-k">object</span> <span class="tok-nc">HotItemsSQL</span> <span class="tok-o">{</span>

  <span class="tok-k">def</span> <span class="tok-n">main</span><span class="tok-o">(</span><span class="tok-n">args</span><span class="tok-k">:</span> <span class="tok-kt">Array</span><span class="tok-o">[</span><span class="tok-kt">String</span><span class="tok-o">])</span><span class="tok-k">:</span> <span class="tok-kt">Unit</span> <span class="tok-o">=</span> <span class="tok-o">{</span>

    <span class="tok-k">val</span> <span class="tok-n">env</span> <span class="tok-k">=</span> <span class="tok-nc">StreamExecutionEnvironment</span><span class="tok-o">.</span><span class="tok-n">getExecutionEnvironment</span>
    <span class="tok-k">val</span> <span class="tok-n">settings</span> <span class="tok-k">=</span> <span class="tok-nc">EnvironmentSettings</span><span class="tok-o">.</span><span class="tok-n">newInstance</span><span class="tok-o">()</span>
      <span class="tok-o">.</span><span class="tok-n">useBlinkPlanner</span><span class="tok-o">()</span>
      <span class="tok-o">.</span><span class="tok-n">inStreamingMode</span><span class="tok-o">()</span>
      <span class="tok-o">.</span><span class="tok-n">build</span><span class="tok-o">()</span>
    <span class="tok-k">val</span> <span class="tok-n">tEnv</span> <span class="tok-k">=</span> <span class="tok-nc">StreamTableEnvironment</span><span class="tok-o">.</span><span class="tok-n">create</span><span class="tok-o">(</span><span class="tok-n">env</span><span class="tok-o">,</span> <span class="tok-n">settings</span><span class="tok-o">)</span>
    <span class="tok-n">env</span><span class="tok-o">.</span><span class="tok-n">setParallelism</span><span class="tok-o">(</span><span class="tok-mi">1</span><span class="tok-o">)</span>
    <span class="tok-n">env</span><span class="tok-o">.</span><span class="tok-n">setStreamTimeCharacteristic</span><span class="tok-o">(</span><span class="tok-nc">TimeCharacteristic</span><span class="tok-o">.</span><span class="tok-nc">EventTime</span><span class="tok-o">)</span>
    <span class="tok-k">val</span> <span class="tok-n">stream</span> <span class="tok-k">=</span> <span class="tok-n">env</span>
      <span class="tok-o">.</span><span class="tok-n">readTextFile</span><span class="tok-o">(</span><span class="tok-s">&quot;/home/parallels/flink-tutorial/Flink0830Tutorial/src/main/resources/UserBehavior.csv&quot;</span><span class="tok-o">)</span>
      <span class="tok-o">.</span><span class="tok-n">map</span><span class="tok-o">(</span><span class="tok-n">line</span> <span class="tok-k">=&gt;</span> <span class="tok-o">{</span>
        <span class="tok-k">val</span> <span class="tok-n">arr</span> <span class="tok-k">=</span> <span class="tok-n">line</span><span class="tok-o">.</span><span class="tok-n">split</span><span class="tok-o">(</span><span class="tok-s">&quot;,&quot;</span><span class="tok-o">)</span>
        <span class="tok-nc">UserBehavior</span><span class="tok-o">(</span><span class="tok-n">arr</span><span class="tok-o">(</span><span class="tok-mi">0</span><span class="tok-o">).</span><span class="tok-n">toLong</span><span class="tok-o">,</span> <span class="tok-n">arr</span><span class="tok-o">(</span><span class="tok-mi">1</span><span class="tok-o">).</span><span class="tok-n">toLong</span><span class="tok-o">,</span> <span class="tok-n">arr</span><span class="tok-o">(</span><span class="tok-mi">2</span><span class="tok-o">).</span><span class="tok-n">toInt</span><span class="tok-o">,</span> <span class="tok-n">arr</span><span class="tok-o">(</span><span class="tok-mi">3</span><span class="tok-o">),</span> <span class="tok-n">arr</span><span class="tok-o">(</span><span class="tok-mi">4</span><span class="tok-o">).</span><span class="tok-n">toLong</span> <span class="tok-o">*</span> <span class="tok-mi">1000</span><span class="tok-o">)</span>
      <span class="tok-o">})</span>
      <span class="tok-o">.</span><span class="tok-n">filter</span><span class="tok-o">(</span><span class="tok-k">_</span><span class="tok-o">.</span><span class="tok-n">behavior</span> <span class="tok-o">==</span> <span class="tok-s">&quot;pv&quot;</span><span class="tok-o">)</span>
      <span class="tok-o">.</span><span class="tok-n">assignAscendingTimestamps</span><span class="tok-o">(</span><span class="tok-k">_</span><span class="tok-o">.</span><span class="tok-n">timestamp</span><span class="tok-o">)</span>

    <span class="tok-n">tEnv</span><span class="tok-o">.</span><span class="tok-n">createTemporaryView</span><span class="tok-o">(</span><span class="tok-s">&quot;t&quot;</span><span class="tok-o">,</span> <span class="tok-n">stream</span><span class="tok-o">,</span> <span class=" tok--Symbol">&#39;itemId</span><span class="tok-o">,</span> <span class=" tok--Symbol">&#39;timestamp</span><span class="tok-o">.</span><span class="tok-n">rowtime</span> <span class="tok-n">as</span> <span class=" tok--Symbol">&#39;ts</span><span class="tok-o">)</span>

    <span class="tok-k">val</span> <span class="tok-n">result</span> <span class="tok-k">=</span> <span class="tok-n">tEnv</span><span class="tok-o">.</span><span class="tok-n">sqlQuery</span><span class="tok-o">(</span>
      <span class="tok-s">&quot;&quot;&quot;</span>
<span class="tok-s">        |SELECT *</span>
<span class="tok-s">        |FROM (</span>
<span class="tok-s">        |    SELECT *,</span>
<span class="tok-s">        |        ROW_NUMBER() OVER (PARTITION BY windowEnd ORDER BY icount DESC) as row_num</span>
<span class="tok-s">        |    FROM (SELECT count(itemId) as icount, TUMBLE_START(ts, INTERVAL &#39;1&#39; HOUR) as windowEnd FROM t GROUP BY TUMBLE(ts, INTERVAL &#39;1&#39; HOUR), itemId) topn)</span>
<span class="tok-s">        |WHERE row_num &lt;= 5</span>
<span class="tok-s">        |&quot;&quot;&quot;</span><span class="tok-o">.</span><span class="tok-n">stripMargin</span>
    <span class="tok-o">)</span>
    <span class="tok-n">result</span><span class="tok-o">.</span><span class="tok-n">toRetractStream</span><span class="tok-o">[(</span><span class="tok-kt">Long</span>, <span class="tok-kt">Timestamp</span>, <span class="tok-kt">Long</span><span class="tok-o">)].</span><span class="tok-n">print</span><span class="tok-o">()</span>

    <span class="tok-n">env</span><span class="tok-o">.</span><span class="tok-n">execute</span><span class="tok-o">()</span>
  <span class="tok-o">}</span>
<span class="tok-o">}</span></code></pre>
</div>
</div>
</div>
<div class="sect2">
<h3 id="_用户自定义函数">11.7. 用户自定义函数</h3>
<div class="sect3">
<h4 id="_scalar_functions">11.7.1. Scalar Functions</h4>
<div class="paragraph">
<p>例子</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="pygments highlight"><code data-lang="scala"><span></span><span class="tok-k">package</span> <span class="tok-nn">com.atguigu.course</span>

<span class="tok-k">import</span> <span class="tok-nn">org.apache.flink.streaming.api.scala.StreamExecutionEnvironment</span>
<span class="tok-k">import</span> <span class="tok-nn">org.apache.flink.api.scala._</span>
<span class="tok-k">import</span> <span class="tok-nn">org.apache.flink.table.api.</span><span class="tok-o">{</span><span class="tok-nc">EnvironmentSettings</span><span class="tok-o">,</span> <span class="tok-nc">Tumble</span><span class="tok-o">}</span>
<span class="tok-k">import</span> <span class="tok-nn">org.apache.flink.table.api.scala._</span>
<span class="tok-k">import</span> <span class="tok-nn">org.apache.flink.table.functions.ScalarFunction</span>

<span class="tok-k">object</span> <span class="tok-nc">TableUDFExample1</span> <span class="tok-o">{</span>
  <span class="tok-k">def</span> <span class="tok-n">main</span><span class="tok-o">(</span><span class="tok-n">args</span><span class="tok-k">:</span> <span class="tok-kt">Array</span><span class="tok-o">[</span><span class="tok-kt">String</span><span class="tok-o">])</span><span class="tok-k">:</span> <span class="tok-kt">Unit</span> <span class="tok-o">=</span> <span class="tok-o">{</span>
    <span class="tok-k">val</span> <span class="tok-n">env</span> <span class="tok-k">=</span> <span class="tok-nc">StreamExecutionEnvironment</span><span class="tok-o">.</span><span class="tok-n">getExecutionEnvironment</span>
    <span class="tok-k">val</span> <span class="tok-n">settings</span> <span class="tok-k">=</span> <span class="tok-nc">EnvironmentSettings</span><span class="tok-o">.</span><span class="tok-n">newInstance</span><span class="tok-o">()</span>
      <span class="tok-o">.</span><span class="tok-n">useBlinkPlanner</span><span class="tok-o">()</span>
      <span class="tok-o">.</span><span class="tok-n">inStreamingMode</span><span class="tok-o">()</span>
      <span class="tok-o">.</span><span class="tok-n">build</span><span class="tok-o">()</span>
    <span class="tok-k">val</span> <span class="tok-n">tEnv</span> <span class="tok-k">=</span> <span class="tok-nc">StreamTableEnvironment</span><span class="tok-o">.</span><span class="tok-n">create</span><span class="tok-o">(</span><span class="tok-n">env</span><span class="tok-o">,</span> <span class="tok-n">settings</span><span class="tok-o">)</span>
    <span class="tok-n">env</span><span class="tok-o">.</span><span class="tok-n">setParallelism</span><span class="tok-o">(</span><span class="tok-mi">1</span><span class="tok-o">)</span>
    <span class="tok-k">val</span> <span class="tok-n">stream</span> <span class="tok-k">=</span> <span class="tok-n">env</span><span class="tok-o">.</span><span class="tok-n">addSource</span><span class="tok-o">(</span><span class="tok-k">new</span> <span class="tok-nc">SensorSource</span><span class="tok-o">)</span>
    <span class="tok-k">val</span> <span class="tok-n">hashCode</span> <span class="tok-k">=</span> <span class="tok-k">new</span> <span class="tok-nc">HashCode</span><span class="tok-o">(</span><span class="tok-mi">10</span><span class="tok-o">)</span>
    <span class="tok-n">tEnv</span><span class="tok-o">.</span><span class="tok-n">registerFunction</span><span class="tok-o">(</span><span class="tok-s">&quot;hashCode&quot;</span><span class="tok-o">,</span> <span class="tok-k">new</span> <span class="tok-nc">HashCode</span><span class="tok-o">(</span><span class="tok-mi">10</span><span class="tok-o">))</span>
    <span class="tok-k">val</span> <span class="tok-n">table</span> <span class="tok-k">=</span> <span class="tok-n">tEnv</span><span class="tok-o">.</span><span class="tok-n">fromDataStream</span><span class="tok-o">(</span><span class="tok-n">stream</span><span class="tok-o">,</span> <span class=" tok--Symbol">&#39;id</span><span class="tok-o">)</span>
    <span class="tok-c1">// table api 写法</span>
    <span class="tok-n">table</span>
      <span class="tok-o">.</span><span class="tok-n">select</span><span class="tok-o">(</span><span class=" tok--Symbol">&#39;id</span><span class="tok-o">,</span> <span class="tok-n">hashCode</span><span class="tok-o">(</span><span class=" tok--Symbol">&#39;id</span><span class="tok-o">))</span>
      <span class="tok-o">.</span><span class="tok-n">toAppendStream</span><span class="tok-o">[(</span><span class="tok-kt">String</span>, <span class="tok-kt">Int</span><span class="tok-o">)]</span>
      <span class="tok-o">.</span><span class="tok-n">print</span><span class="tok-o">()</span>

    <span class="tok-c1">// sql 写法</span>
    <span class="tok-n">tEnv</span><span class="tok-o">.</span><span class="tok-n">createTemporaryView</span><span class="tok-o">(</span><span class="tok-s">&quot;t&quot;</span><span class="tok-o">,</span> <span class="tok-n">table</span><span class="tok-o">,</span> <span class=" tok--Symbol">&#39;id</span><span class="tok-o">)</span>
    <span class="tok-n">tEnv</span>
      <span class="tok-o">.</span><span class="tok-n">sqlQuery</span><span class="tok-o">(</span><span class="tok-s">&quot;SELECT id, hashCode(id) FROM t&quot;</span><span class="tok-o">)</span>
      <span class="tok-o">.</span><span class="tok-n">toAppendStream</span><span class="tok-o">[(</span><span class="tok-kt">String</span>, <span class="tok-kt">Int</span><span class="tok-o">)]</span>
      <span class="tok-o">.</span><span class="tok-n">print</span><span class="tok-o">()</span>

    <span class="tok-n">env</span><span class="tok-o">.</span><span class="tok-n">execute</span><span class="tok-o">()</span>
  <span class="tok-o">}</span>

  <span class="tok-k">class</span> <span class="tok-nc">HashCode</span><span class="tok-o">(</span><span class="tok-n">factor</span><span class="tok-k">:</span> <span class="tok-kt">Int</span><span class="tok-o">)</span> <span class="tok-k">extends</span> <span class="tok-nc">ScalarFunction</span> <span class="tok-o">{</span>
    <span class="tok-k">def</span> <span class="tok-n">eval</span><span class="tok-o">(</span><span class="tok-n">s</span><span class="tok-k">:</span> <span class="tok-kt">String</span><span class="tok-o">)</span><span class="tok-k">:</span> <span class="tok-kt">Int</span> <span class="tok-o">=</span> <span class="tok-o">{</span>
      <span class="tok-n">s</span><span class="tok-o">.</span><span class="tok-n">hashCode</span><span class="tok-o">()</span> <span class="tok-o">*</span> <span class="tok-n">factor</span>
    <span class="tok-o">}</span>
  <span class="tok-o">}</span>

<span class="tok-o">}</span></code></pre>
</div>
</div>
</div>
<div class="sect3">
<h4 id="_table_functions">11.7.2. Table Functions</h4>
<div class="listingblock">
<div class="content">
<pre class="pygments highlight"><code data-lang="scala"><span></span><span class="tok-k">package</span> <span class="tok-nn">com.atguigu.course</span>

<span class="tok-k">import</span> <span class="tok-nn">org.apache.flink.streaming.api.scala.StreamExecutionEnvironment</span>
<span class="tok-k">import</span> <span class="tok-nn">org.apache.flink.api.scala._</span>
<span class="tok-k">import</span> <span class="tok-nn">org.apache.flink.table.api.</span><span class="tok-o">{</span><span class="tok-nc">EnvironmentSettings</span><span class="tok-o">,</span> <span class="tok-nc">Tumble</span><span class="tok-o">}</span>
<span class="tok-k">import</span> <span class="tok-nn">org.apache.flink.table.api.scala._</span>
<span class="tok-k">import</span> <span class="tok-nn">org.apache.flink.table.functions.TableFunction</span>

<span class="tok-k">object</span> <span class="tok-nc">TableUDFExample2</span> <span class="tok-o">{</span>
  <span class="tok-k">def</span> <span class="tok-n">main</span><span class="tok-o">(</span><span class="tok-n">args</span><span class="tok-k">:</span> <span class="tok-kt">Array</span><span class="tok-o">[</span><span class="tok-kt">String</span><span class="tok-o">])</span><span class="tok-k">:</span> <span class="tok-kt">Unit</span> <span class="tok-o">=</span> <span class="tok-o">{</span>
    <span class="tok-k">val</span> <span class="tok-n">env</span> <span class="tok-k">=</span> <span class="tok-nc">StreamExecutionEnvironment</span><span class="tok-o">.</span><span class="tok-n">getExecutionEnvironment</span>
    <span class="tok-k">val</span> <span class="tok-n">settings</span> <span class="tok-k">=</span> <span class="tok-nc">EnvironmentSettings</span><span class="tok-o">.</span><span class="tok-n">newInstance</span><span class="tok-o">()</span>
      <span class="tok-o">.</span><span class="tok-n">useBlinkPlanner</span><span class="tok-o">()</span>
      <span class="tok-o">.</span><span class="tok-n">inStreamingMode</span><span class="tok-o">()</span>
      <span class="tok-o">.</span><span class="tok-n">build</span><span class="tok-o">()</span>
    <span class="tok-k">val</span> <span class="tok-n">tEnv</span> <span class="tok-k">=</span> <span class="tok-nc">StreamTableEnvironment</span><span class="tok-o">.</span><span class="tok-n">create</span><span class="tok-o">(</span><span class="tok-n">env</span><span class="tok-o">,</span> <span class="tok-n">settings</span><span class="tok-o">)</span>
    <span class="tok-k">val</span> <span class="tok-n">split</span> <span class="tok-k">=</span> <span class="tok-k">new</span> <span class="tok-nc">Split</span><span class="tok-o">(</span><span class="tok-s">&quot;#&quot;</span><span class="tok-o">)</span>
    <span class="tok-n">env</span><span class="tok-o">.</span><span class="tok-n">setParallelism</span><span class="tok-o">(</span><span class="tok-mi">1</span><span class="tok-o">)</span>
    <span class="tok-k">val</span> <span class="tok-n">stream</span> <span class="tok-k">=</span> <span class="tok-n">env</span><span class="tok-o">.</span><span class="tok-n">fromElements</span><span class="tok-o">(</span>
      <span class="tok-s">&quot;hello#world&quot;</span>
    <span class="tok-o">)</span>
    <span class="tok-k">val</span> <span class="tok-n">table</span> <span class="tok-k">=</span> <span class="tok-n">tEnv</span><span class="tok-o">.</span><span class="tok-n">fromDataStream</span><span class="tok-o">(</span><span class="tok-n">stream</span><span class="tok-o">,</span> <span class=" tok--Symbol">&#39;s</span><span class="tok-o">)</span>
    <span class="tok-c1">// table api 写法</span>
    <span class="tok-n">table</span>
      <span class="tok-o">.</span><span class="tok-n">joinLateral</span><span class="tok-o">(</span><span class="tok-n">split</span><span class="tok-o">(</span><span class=" tok--Symbol">&#39;s</span><span class="tok-o">)</span> <span class="tok-n">as</span> <span class="tok-o">(</span><span class=" tok--Symbol">&#39;word</span><span class="tok-o">,</span> <span class=" tok--Symbol">&#39;length</span><span class="tok-o">))</span>
      <span class="tok-o">.</span><span class="tok-n">select</span><span class="tok-o">(</span><span class=" tok--Symbol">&#39;s</span><span class="tok-o">,</span> <span class=" tok--Symbol">&#39;word</span><span class="tok-o">,</span> <span class=" tok--Symbol">&#39;length</span><span class="tok-o">)</span>
      <span class="tok-o">.</span><span class="tok-n">toAppendStream</span><span class="tok-o">[(</span><span class="tok-kt">String</span>, <span class="tok-kt">String</span>, <span class="tok-kt">Long</span><span class="tok-o">)]</span>
      <span class="tok-o">.</span><span class="tok-n">print</span><span class="tok-o">()</span>
    <span class="tok-n">table</span>
      <span class="tok-o">.</span><span class="tok-n">leftOuterJoinLateral</span><span class="tok-o">(</span><span class="tok-n">split</span><span class="tok-o">(</span><span class=" tok--Symbol">&#39;s</span><span class="tok-o">)</span> <span class="tok-n">as</span> <span class="tok-o">(</span><span class=" tok--Symbol">&#39;word</span><span class="tok-o">,</span> <span class=" tok--Symbol">&#39;length</span><span class="tok-o">))</span>
      <span class="tok-o">.</span><span class="tok-n">select</span><span class="tok-o">(</span><span class=" tok--Symbol">&#39;s</span><span class="tok-o">,</span> <span class=" tok--Symbol">&#39;word</span><span class="tok-o">,</span> <span class=" tok--Symbol">&#39;length</span><span class="tok-o">)</span>
      <span class="tok-o">.</span><span class="tok-n">toAppendStream</span><span class="tok-o">[(</span><span class="tok-kt">String</span>, <span class="tok-kt">String</span>, <span class="tok-kt">Long</span><span class="tok-o">)]</span>
      <span class="tok-o">.</span><span class="tok-n">print</span><span class="tok-o">()</span>

    <span class="tok-c1">// sql 写法</span>
    <span class="tok-n">tEnv</span><span class="tok-o">.</span><span class="tok-n">registerFunction</span><span class="tok-o">(</span><span class="tok-s">&quot;split&quot;</span><span class="tok-o">,</span> <span class="tok-k">new</span> <span class="tok-nc">Split</span><span class="tok-o">(</span><span class="tok-s">&quot;#&quot;</span><span class="tok-o">))</span>

    <span class="tok-n">tEnv</span><span class="tok-o">.</span><span class="tok-n">createTemporaryView</span><span class="tok-o">(</span><span class="tok-s">&quot;t&quot;</span><span class="tok-o">,</span> <span class="tok-n">table</span><span class="tok-o">,</span> <span class=" tok--Symbol">&#39;s</span><span class="tok-o">)</span>

    <span class="tok-c1">// Use the table function in SQL with LATERAL and TABLE keywords.</span>
    <span class="tok-c1">// CROSS JOIN a table function (equivalent to &quot;join&quot; in Table API)</span>
    <span class="tok-n">tEnv</span>
      <span class="tok-o">.</span><span class="tok-n">sqlQuery</span><span class="tok-o">(</span><span class="tok-s">&quot;SELECT s, word, length FROM t, LATERAL TABLE(split(s)) as T(word, length)&quot;</span><span class="tok-o">)</span>
      <span class="tok-o">.</span><span class="tok-n">toAppendStream</span><span class="tok-o">[(</span><span class="tok-kt">String</span>, <span class="tok-kt">String</span>, <span class="tok-kt">Int</span><span class="tok-o">)]</span>
      <span class="tok-o">.</span><span class="tok-n">print</span><span class="tok-o">()</span>
    <span class="tok-c1">// LEFT JOIN a table function (equivalent to &quot;leftOuterJoin&quot; in Table API)</span>
    <span class="tok-n">tEnv</span>
      <span class="tok-o">.</span><span class="tok-n">sqlQuery</span><span class="tok-o">(</span><span class="tok-s">&quot;SELECT s, word, length FROM t LEFT JOIN LATERAL TABLE(split(s)) as T(word, length) ON TRUE&quot;</span><span class="tok-o">)</span>
      <span class="tok-o">.</span><span class="tok-n">toAppendStream</span><span class="tok-o">[(</span><span class="tok-kt">String</span>, <span class="tok-kt">String</span>, <span class="tok-kt">Int</span><span class="tok-o">)]</span>
      <span class="tok-o">.</span><span class="tok-n">print</span><span class="tok-o">()</span>

    <span class="tok-n">env</span><span class="tok-o">.</span><span class="tok-n">execute</span><span class="tok-o">()</span>

  <span class="tok-o">}</span>
  <span class="tok-k">class</span> <span class="tok-nc">Split</span><span class="tok-o">(</span><span class="tok-n">separator</span><span class="tok-k">:</span> <span class="tok-kt">String</span><span class="tok-o">)</span> <span class="tok-k">extends</span> <span class="tok-nc">TableFunction</span><span class="tok-o">[(</span><span class="tok-kt">String</span>, <span class="tok-kt">Int</span><span class="tok-o">)]</span> <span class="tok-o">{</span>
    <span class="tok-k">def</span> <span class="tok-n">eval</span><span class="tok-o">(</span><span class="tok-n">str</span><span class="tok-k">:</span> <span class="tok-kt">String</span><span class="tok-o">)</span><span class="tok-k">:</span> <span class="tok-kt">Unit</span> <span class="tok-o">=</span> <span class="tok-o">{</span>
      <span class="tok-c1">// use collect(...) to emit a row.</span>
      <span class="tok-n">str</span><span class="tok-o">.</span><span class="tok-n">split</span><span class="tok-o">(</span><span class="tok-n">separator</span><span class="tok-o">).</span><span class="tok-n">foreach</span><span class="tok-o">(</span><span class="tok-n">x</span> <span class="tok-k">=&gt;</span> <span class="tok-n">collect</span><span class="tok-o">((</span><span class="tok-n">x</span><span class="tok-o">,</span> <span class="tok-n">x</span><span class="tok-o">.</span><span class="tok-n">length</span><span class="tok-o">)))</span>
    <span class="tok-o">}</span>
  <span class="tok-o">}</span>
<span class="tok-o">}</span></code></pre>
</div>
</div>
</div>
<div class="sect3">
<h4 id="_aggregation_functions">11.7.3. Aggregation Functions</h4>
<div class="paragraph">
<p>例子</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="pygments highlight"><code data-lang="scala"><span></span><span class="tok-k">package</span> <span class="tok-nn">com.atguigu.course</span>

<span class="tok-k">import</span> <span class="tok-nn">org.apache.flink.api.common.typeinfo.TypeInformation</span>
<span class="tok-k">import</span> <span class="tok-nn">org.apache.flink.api.java.typeutils.</span><span class="tok-o">{</span><span class="tok-nc">RowTypeInfo</span><span class="tok-o">,</span> <span class="tok-nc">TupleTypeInfo</span><span class="tok-o">}</span>
<span class="tok-k">import</span> <span class="tok-nn">org.apache.flink.streaming.api.scala.StreamExecutionEnvironment</span>
<span class="tok-k">import</span> <span class="tok-nn">org.apache.flink.api.scala._</span>
<span class="tok-k">import</span> <span class="tok-nn">org.apache.flink.table.api.</span><span class="tok-o">{</span><span class="tok-nc">EnvironmentSettings</span><span class="tok-o">,</span> <span class="tok-nc">Tumble</span><span class="tok-o">}</span>
<span class="tok-k">import</span> <span class="tok-nn">org.apache.flink.table.api.scala._</span>
<span class="tok-k">import</span> <span class="tok-nn">org.apache.flink.table.functions.AggregateFunction</span>
<span class="tok-k">import</span> <span class="tok-nn">org.apache.flink.table.api.Types</span>
<span class="tok-k">import</span> <span class="tok-nn">org.apache.flink.types.Row</span>

<span class="tok-k">object</span> <span class="tok-nc">TableUDFExample3</span> <span class="tok-o">{</span>
  <span class="tok-k">def</span> <span class="tok-n">main</span><span class="tok-o">(</span><span class="tok-n">args</span><span class="tok-k">:</span> <span class="tok-kt">Array</span><span class="tok-o">[</span><span class="tok-kt">String</span><span class="tok-o">])</span><span class="tok-k">:</span> <span class="tok-kt">Unit</span> <span class="tok-o">=</span> <span class="tok-o">{</span>
    <span class="tok-k">val</span> <span class="tok-n">env</span> <span class="tok-k">=</span> <span class="tok-nc">StreamExecutionEnvironment</span><span class="tok-o">.</span><span class="tok-n">getExecutionEnvironment</span>
    <span class="tok-k">val</span> <span class="tok-n">settings</span> <span class="tok-k">=</span> <span class="tok-nc">EnvironmentSettings</span><span class="tok-o">.</span><span class="tok-n">newInstance</span><span class="tok-o">()</span>
      <span class="tok-o">.</span><span class="tok-n">useBlinkPlanner</span><span class="tok-o">()</span>
      <span class="tok-o">.</span><span class="tok-n">inStreamingMode</span><span class="tok-o">()</span>
      <span class="tok-o">.</span><span class="tok-n">build</span><span class="tok-o">()</span>
    <span class="tok-k">val</span> <span class="tok-n">tEnv</span> <span class="tok-k">=</span> <span class="tok-nc">StreamTableEnvironment</span><span class="tok-o">.</span><span class="tok-n">create</span><span class="tok-o">(</span><span class="tok-n">env</span><span class="tok-o">,</span> <span class="tok-n">settings</span><span class="tok-o">)</span>
    <span class="tok-k">val</span> <span class="tok-n">myAggFunc</span> <span class="tok-k">=</span> <span class="tok-k">new</span> <span class="tok-nc">MyMinMax</span>
    <span class="tok-n">env</span><span class="tok-o">.</span><span class="tok-n">setParallelism</span><span class="tok-o">(</span><span class="tok-mi">1</span><span class="tok-o">)</span>
    <span class="tok-k">val</span> <span class="tok-n">stream</span> <span class="tok-k">=</span> <span class="tok-n">env</span><span class="tok-o">.</span><span class="tok-n">fromElements</span><span class="tok-o">(</span>
      <span class="tok-o">(</span><span class="tok-mi">1</span><span class="tok-o">,</span> <span class="tok-o">-</span><span class="tok-mi">1</span><span class="tok-o">),</span>
      <span class="tok-o">(</span><span class="tok-mi">1</span><span class="tok-o">,</span> <span class="tok-mi">2</span><span class="tok-o">)</span>
    <span class="tok-o">)</span>
    <span class="tok-k">val</span> <span class="tok-n">table</span> <span class="tok-k">=</span> <span class="tok-n">tEnv</span><span class="tok-o">.</span><span class="tok-n">fromDataStream</span><span class="tok-o">(</span><span class="tok-n">stream</span><span class="tok-o">,</span> <span class=" tok--Symbol">&#39;key</span><span class="tok-o">,</span> <span class=" tok--Symbol">&#39;a</span><span class="tok-o">)</span>
    <span class="tok-n">table</span>
      <span class="tok-o">.</span><span class="tok-n">groupBy</span><span class="tok-o">(</span><span class=" tok--Symbol">&#39;key</span><span class="tok-o">)</span>
      <span class="tok-o">.</span><span class="tok-n">aggregate</span><span class="tok-o">(</span><span class="tok-n">myAggFunc</span><span class="tok-o">(</span><span class=" tok--Symbol">&#39;a</span><span class="tok-o">)</span> <span class="tok-n">as</span> <span class="tok-o">(</span><span class=" tok--Symbol">&#39;x</span><span class="tok-o">,</span> <span class=" tok--Symbol">&#39;y</span><span class="tok-o">))</span>
      <span class="tok-o">.</span><span class="tok-n">select</span><span class="tok-o">(</span><span class=" tok--Symbol">&#39;key</span><span class="tok-o">,</span> <span class=" tok--Symbol">&#39;x</span><span class="tok-o">,</span> <span class=" tok--Symbol">&#39;y</span><span class="tok-o">)</span>
      <span class="tok-o">.</span><span class="tok-n">toRetractStream</span><span class="tok-o">[(</span><span class="tok-kt">Long</span>, <span class="tok-kt">Long</span>, <span class="tok-kt">Long</span><span class="tok-o">)]</span>
      <span class="tok-o">.</span><span class="tok-n">print</span><span class="tok-o">()</span>

    <span class="tok-n">env</span><span class="tok-o">.</span><span class="tok-n">execute</span><span class="tok-o">()</span>
  <span class="tok-o">}</span>

  <span class="tok-k">case</span> <span class="tok-k">class</span> <span class="tok-nc">MyMinMaxAcc</span><span class="tok-o">(</span><span class="tok-k">var</span> <span class="tok-n">min</span><span class="tok-k">:</span> <span class="tok-kt">Int</span><span class="tok-o">,</span> <span class="tok-k">var</span> <span class="tok-n">max</span><span class="tok-k">:</span> <span class="tok-kt">Int</span><span class="tok-o">)</span>

  <span class="tok-k">class</span> <span class="tok-nc">MyMinMax</span> <span class="tok-k">extends</span> <span class="tok-nc">AggregateFunction</span><span class="tok-o">[</span><span class="tok-kt">Row</span>, <span class="tok-kt">MyMinMaxAcc</span><span class="tok-o">]</span> <span class="tok-o">{</span>

    <span class="tok-k">def</span> <span class="tok-n">accumulate</span><span class="tok-o">(</span><span class="tok-n">acc</span><span class="tok-k">:</span> <span class="tok-kt">MyMinMaxAcc</span><span class="tok-o">,</span> <span class="tok-n">value</span><span class="tok-k">:</span> <span class="tok-kt">Int</span><span class="tok-o">)</span><span class="tok-k">:</span> <span class="tok-kt">Unit</span> <span class="tok-o">=</span> <span class="tok-o">{</span>
      <span class="tok-k">if</span> <span class="tok-o">(</span><span class="tok-n">value</span> <span class="tok-o">&lt;</span> <span class="tok-n">acc</span><span class="tok-o">.</span><span class="tok-n">min</span><span class="tok-o">)</span> <span class="tok-o">{</span>
        <span class="tok-n">acc</span><span class="tok-o">.</span><span class="tok-n">min</span> <span class="tok-k">=</span> <span class="tok-n">value</span>
      <span class="tok-o">}</span>
      <span class="tok-k">if</span> <span class="tok-o">(</span><span class="tok-n">value</span> <span class="tok-o">&gt;</span> <span class="tok-n">acc</span><span class="tok-o">.</span><span class="tok-n">max</span><span class="tok-o">)</span> <span class="tok-o">{</span>
        <span class="tok-n">acc</span><span class="tok-o">.</span><span class="tok-n">max</span> <span class="tok-k">=</span> <span class="tok-n">value</span>
      <span class="tok-o">}</span>
    <span class="tok-o">}</span>

    <span class="tok-k">override</span> <span class="tok-k">def</span> <span class="tok-n">createAccumulator</span><span class="tok-o">()</span><span class="tok-k">:</span> <span class="tok-kt">MyMinMaxAcc</span> <span class="tok-o">=</span> <span class="tok-nc">MyMinMaxAcc</span><span class="tok-o">(</span><span class="tok-mi">0</span><span class="tok-o">,</span> <span class="tok-mi">0</span><span class="tok-o">)</span>

    <span class="tok-k">def</span> <span class="tok-n">resetAccumulator</span><span class="tok-o">(</span><span class="tok-n">acc</span><span class="tok-k">:</span> <span class="tok-kt">MyMinMaxAcc</span><span class="tok-o">)</span><span class="tok-k">:</span> <span class="tok-kt">Unit</span> <span class="tok-o">=</span> <span class="tok-o">{</span>
      <span class="tok-n">acc</span><span class="tok-o">.</span><span class="tok-n">min</span> <span class="tok-k">=</span> <span class="tok-mi">0</span>
      <span class="tok-n">acc</span><span class="tok-o">.</span><span class="tok-n">max</span> <span class="tok-k">=</span> <span class="tok-mi">0</span>
    <span class="tok-o">}</span>

    <span class="tok-k">override</span> <span class="tok-k">def</span> <span class="tok-n">getValue</span><span class="tok-o">(</span><span class="tok-n">acc</span><span class="tok-k">:</span> <span class="tok-kt">MyMinMaxAcc</span><span class="tok-o">)</span><span class="tok-k">:</span> <span class="tok-kt">Row</span> <span class="tok-o">=</span> <span class="tok-o">{</span>
      <span class="tok-nc">Row</span><span class="tok-o">.</span><span class="tok-n">of</span><span class="tok-o">(</span><span class="tok-nc">Integer</span><span class="tok-o">.</span><span class="tok-n">valueOf</span><span class="tok-o">(</span><span class="tok-n">acc</span><span class="tok-o">.</span><span class="tok-n">min</span><span class="tok-o">),</span> <span class="tok-nc">Integer</span><span class="tok-o">.</span><span class="tok-n">valueOf</span><span class="tok-o">(</span><span class="tok-n">acc</span><span class="tok-o">.</span><span class="tok-n">max</span><span class="tok-o">))</span>
    <span class="tok-o">}</span>

    <span class="tok-k">override</span> <span class="tok-k">def</span> <span class="tok-n">getResultType</span><span class="tok-k">:</span> <span class="tok-kt">TypeInformation</span><span class="tok-o">[</span><span class="tok-kt">Row</span><span class="tok-o">]</span> <span class="tok-k">=</span> <span class="tok-o">{</span>
      <span class="tok-k">new</span> <span class="tok-nc">RowTypeInfo</span><span class="tok-o">(</span><span class="tok-nc">Types</span><span class="tok-o">.</span><span class="tok-nc">INT</span><span class="tok-o">,</span> <span class="tok-nc">Types</span><span class="tok-o">.</span><span class="tok-nc">INT</span><span class="tok-o">)</span>
    <span class="tok-o">}</span>
  <span class="tok-o">}</span>
<span class="tok-o">}</span></code></pre>
</div>
</div>
</div>
<div class="sect3">
<h4 id="_table_aggregation_functions">11.7.4. Table Aggregation Functions</h4>
<div class="paragraph">
<p>例子</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="pygments highlight"><code data-lang="scala"><span></span><span class="tok-k">package</span> <span class="tok-nn">com.atguigu.course</span>

<span class="tok-k">import</span> <span class="tok-nn">java.lang.</span><span class="tok-o">{</span><span class="tok-nc">Integer</span> <span class="tok-k">=&gt;</span> <span class="tok-nc">JInteger</span><span class="tok-o">}</span>

<span class="tok-k">import</span> <span class="tok-nn">org.apache.flink.table.functions.TableAggregateFunction</span>
<span class="tok-k">import</span> <span class="tok-nn">org.apache.flink.api.scala._</span>
<span class="tok-k">import</span> <span class="tok-nn">org.apache.flink.streaming.api.scala.StreamExecutionEnvironment</span>
<span class="tok-k">import</span> <span class="tok-nn">org.apache.flink.table.api.EnvironmentSettings</span>
<span class="tok-k">import</span> <span class="tok-nn">org.apache.flink.table.api.scala._</span>
<span class="tok-k">import</span> <span class="tok-nn">org.apache.flink.api.java.tuple.</span><span class="tok-o">{</span><span class="tok-nc">Tuple2</span> <span class="tok-k">=&gt;</span> <span class="tok-nc">JTuple2</span><span class="tok-o">}</span>
<span class="tok-k">import</span> <span class="tok-nn">java.lang.</span><span class="tok-o">{</span><span class="tok-nc">Iterable</span> <span class="tok-k">=&gt;</span> <span class="tok-nc">JIterable</span><span class="tok-o">}</span>

<span class="tok-k">import</span> <span class="tok-nn">org.apache.flink.util.Collector</span>

<span class="tok-k">object</span> <span class="tok-nc">TableUDFExample4</span> <span class="tok-o">{</span>
  <span class="tok-k">def</span> <span class="tok-n">main</span><span class="tok-o">(</span><span class="tok-n">args</span><span class="tok-k">:</span> <span class="tok-kt">Array</span><span class="tok-o">[</span><span class="tok-kt">String</span><span class="tok-o">])</span><span class="tok-k">:</span> <span class="tok-kt">Unit</span> <span class="tok-o">=</span> <span class="tok-o">{</span>
    <span class="tok-k">val</span> <span class="tok-n">env</span> <span class="tok-k">=</span> <span class="tok-nc">StreamExecutionEnvironment</span><span class="tok-o">.</span><span class="tok-n">getExecutionEnvironment</span>
    <span class="tok-k">val</span> <span class="tok-n">settings</span> <span class="tok-k">=</span> <span class="tok-nc">EnvironmentSettings</span><span class="tok-o">.</span><span class="tok-n">newInstance</span><span class="tok-o">()</span>
      <span class="tok-o">.</span><span class="tok-n">useBlinkPlanner</span><span class="tok-o">()</span>
      <span class="tok-o">.</span><span class="tok-n">inStreamingMode</span><span class="tok-o">()</span>
      <span class="tok-o">.</span><span class="tok-n">build</span><span class="tok-o">()</span>
    <span class="tok-k">val</span> <span class="tok-n">tEnv</span> <span class="tok-k">=</span> <span class="tok-nc">StreamTableEnvironment</span><span class="tok-o">.</span><span class="tok-n">create</span><span class="tok-o">(</span><span class="tok-n">env</span><span class="tok-o">,</span> <span class="tok-n">settings</span><span class="tok-o">)</span>
    <span class="tok-n">env</span><span class="tok-o">.</span><span class="tok-n">setParallelism</span><span class="tok-o">(</span><span class="tok-mi">1</span><span class="tok-o">)</span>
    <span class="tok-k">val</span> <span class="tok-n">stream</span> <span class="tok-k">=</span> <span class="tok-n">env</span><span class="tok-o">.</span><span class="tok-n">fromElements</span><span class="tok-o">(</span>
      <span class="tok-o">(</span><span class="tok-mi">1</span><span class="tok-o">,</span> <span class="tok-o">-</span><span class="tok-mi">1</span><span class="tok-o">),</span>
      <span class="tok-o">(</span><span class="tok-mi">1</span><span class="tok-o">,</span> <span class="tok-mi">2</span><span class="tok-o">),</span>
      <span class="tok-o">(</span><span class="tok-mi">1</span><span class="tok-o">,</span> <span class="tok-mi">0</span><span class="tok-o">),</span>
      <span class="tok-o">(</span><span class="tok-mi">1</span><span class="tok-o">,</span> <span class="tok-mi">5</span><span class="tok-o">),</span>
      <span class="tok-o">(</span><span class="tok-mi">1</span><span class="tok-o">,</span> <span class="tok-mi">4</span><span class="tok-o">)</span>
    <span class="tok-o">)</span>
    <span class="tok-k">val</span> <span class="tok-n">top2</span> <span class="tok-k">=</span> <span class="tok-k">new</span> <span class="tok-nc">Top2</span>
    <span class="tok-k">val</span> <span class="tok-n">table</span> <span class="tok-k">=</span> <span class="tok-n">tEnv</span><span class="tok-o">.</span><span class="tok-n">fromDataStream</span><span class="tok-o">(</span><span class="tok-n">stream</span><span class="tok-o">,</span> <span class=" tok--Symbol">&#39;key</span><span class="tok-o">,</span> <span class=" tok--Symbol">&#39;a</span><span class="tok-o">)</span>
    <span class="tok-n">table</span>
      <span class="tok-o">.</span><span class="tok-n">groupBy</span><span class="tok-o">(</span><span class=" tok--Symbol">&#39;key</span><span class="tok-o">)</span>
      <span class="tok-o">.</span><span class="tok-n">flatAggregate</span><span class="tok-o">(</span><span class="tok-n">top2</span><span class="tok-o">(</span><span class=" tok--Symbol">&#39;a</span><span class="tok-o">)</span> <span class="tok-n">as</span> <span class="tok-o">(</span><span class=" tok--Symbol">&#39;v</span><span class="tok-o">,</span> <span class=" tok--Symbol">&#39;rank</span><span class="tok-o">))</span>
      <span class="tok-o">.</span><span class="tok-n">select</span><span class="tok-o">(</span><span class=" tok--Symbol">&#39;key</span><span class="tok-o">,</span> <span class=" tok--Symbol">&#39;v</span><span class="tok-o">,</span> <span class=" tok--Symbol">&#39;rank</span><span class="tok-o">)</span>
      <span class="tok-o">.</span><span class="tok-n">toRetractStream</span><span class="tok-o">[(</span><span class="tok-kt">Long</span>, <span class="tok-kt">Long</span>, <span class="tok-kt">Long</span><span class="tok-o">)]</span>
      <span class="tok-o">.</span><span class="tok-n">print</span><span class="tok-o">()</span>

    <span class="tok-n">env</span><span class="tok-o">.</span><span class="tok-n">execute</span><span class="tok-o">()</span>
  <span class="tok-o">}</span>

  <span class="tok-cm">/**</span>
<span class="tok-cm">   * Accumulator for top2.</span>
<span class="tok-cm">   */</span>
  <span class="tok-k">class</span> <span class="tok-nc">Top2Accum</span> <span class="tok-o">{</span>
    <span class="tok-k">var</span> <span class="tok-n">first</span><span class="tok-k">:</span> <span class="tok-kt">JInteger</span> <span class="tok-o">=</span> <span class="tok-k">_</span>
    <span class="tok-k">var</span> <span class="tok-n">second</span><span class="tok-k">:</span> <span class="tok-kt">JInteger</span> <span class="tok-o">=</span> <span class="tok-k">_</span>
  <span class="tok-o">}</span>

  <span class="tok-cm">/**</span>
<span class="tok-cm">   * The top2 user-defined table aggregate function.</span>
<span class="tok-cm">   */</span>
  <span class="tok-k">class</span> <span class="tok-nc">Top2</span> <span class="tok-k">extends</span> <span class="tok-nc">TableAggregateFunction</span><span class="tok-o">[</span><span class="tok-kt">JTuple2</span><span class="tok-o">[</span><span class="tok-kt">JInteger</span>, <span class="tok-kt">JInteger</span><span class="tok-o">]</span>, <span class="tok-kt">Top2Accum</span><span class="tok-o">]</span> <span class="tok-o">{</span>

    <span class="tok-k">override</span> <span class="tok-k">def</span> <span class="tok-n">createAccumulator</span><span class="tok-o">()</span><span class="tok-k">:</span> <span class="tok-kt">Top2Accum</span> <span class="tok-o">=</span> <span class="tok-o">{</span>
      <span class="tok-k">val</span> <span class="tok-n">acc</span> <span class="tok-k">=</span> <span class="tok-k">new</span> <span class="tok-nc">Top2Accum</span>
      <span class="tok-n">acc</span><span class="tok-o">.</span><span class="tok-n">first</span> <span class="tok-k">=</span> <span class="tok-nc">Int</span><span class="tok-o">.</span><span class="tok-nc">MinValue</span>
      <span class="tok-n">acc</span><span class="tok-o">.</span><span class="tok-n">second</span> <span class="tok-k">=</span> <span class="tok-nc">Int</span><span class="tok-o">.</span><span class="tok-nc">MinValue</span>
      <span class="tok-n">acc</span>
    <span class="tok-o">}</span>

    <span class="tok-k">def</span> <span class="tok-n">accumulate</span><span class="tok-o">(</span><span class="tok-n">acc</span><span class="tok-k">:</span> <span class="tok-kt">Top2Accum</span><span class="tok-o">,</span> <span class="tok-n">v</span><span class="tok-k">:</span> <span class="tok-kt">Int</span><span class="tok-o">)</span> <span class="tok-o">{</span>
      <span class="tok-k">if</span> <span class="tok-o">(</span><span class="tok-n">v</span> <span class="tok-o">&gt;</span> <span class="tok-n">acc</span><span class="tok-o">.</span><span class="tok-n">first</span><span class="tok-o">)</span> <span class="tok-o">{</span>
        <span class="tok-n">acc</span><span class="tok-o">.</span><span class="tok-n">second</span> <span class="tok-k">=</span> <span class="tok-n">acc</span><span class="tok-o">.</span><span class="tok-n">first</span>
        <span class="tok-n">acc</span><span class="tok-o">.</span><span class="tok-n">first</span> <span class="tok-k">=</span> <span class="tok-n">v</span>
      <span class="tok-o">}</span> <span class="tok-k">else</span> <span class="tok-k">if</span> <span class="tok-o">(</span><span class="tok-n">v</span> <span class="tok-o">&gt;</span> <span class="tok-n">acc</span><span class="tok-o">.</span><span class="tok-n">second</span><span class="tok-o">)</span> <span class="tok-o">{</span>
        <span class="tok-n">acc</span><span class="tok-o">.</span><span class="tok-n">second</span> <span class="tok-k">=</span> <span class="tok-n">v</span>
      <span class="tok-o">}</span>
    <span class="tok-o">}</span>

    <span class="tok-k">def</span> <span class="tok-n">merge</span><span class="tok-o">(</span><span class="tok-n">acc</span><span class="tok-k">:</span> <span class="tok-kt">Top2Accum</span><span class="tok-o">,</span> <span class="tok-n">its</span><span class="tok-k">:</span> <span class="tok-kt">JIterable</span><span class="tok-o">[</span><span class="tok-kt">Top2Accum</span><span class="tok-o">])</span><span class="tok-k">:</span> <span class="tok-kt">Unit</span> <span class="tok-o">=</span> <span class="tok-o">{</span>
      <span class="tok-k">val</span> <span class="tok-n">iter</span> <span class="tok-k">=</span> <span class="tok-n">its</span><span class="tok-o">.</span><span class="tok-n">iterator</span><span class="tok-o">()</span>
      <span class="tok-k">while</span> <span class="tok-o">(</span><span class="tok-n">iter</span><span class="tok-o">.</span><span class="tok-n">hasNext</span><span class="tok-o">)</span> <span class="tok-o">{</span>
        <span class="tok-k">val</span> <span class="tok-n">top2</span> <span class="tok-k">=</span> <span class="tok-n">iter</span><span class="tok-o">.</span><span class="tok-n">next</span><span class="tok-o">()</span>
        <span class="tok-n">accumulate</span><span class="tok-o">(</span><span class="tok-n">acc</span><span class="tok-o">,</span> <span class="tok-n">top2</span><span class="tok-o">.</span><span class="tok-n">first</span><span class="tok-o">)</span>
        <span class="tok-n">accumulate</span><span class="tok-o">(</span><span class="tok-n">acc</span><span class="tok-o">,</span> <span class="tok-n">top2</span><span class="tok-o">.</span><span class="tok-n">second</span><span class="tok-o">)</span>
      <span class="tok-o">}</span>
    <span class="tok-o">}</span>

    <span class="tok-k">def</span> <span class="tok-n">emitValue</span><span class="tok-o">(</span><span class="tok-n">acc</span><span class="tok-k">:</span> <span class="tok-kt">Top2Accum</span><span class="tok-o">,</span> <span class="tok-n">out</span><span class="tok-k">:</span> <span class="tok-kt">Collector</span><span class="tok-o">[</span><span class="tok-kt">JTuple2</span><span class="tok-o">[</span><span class="tok-kt">JInteger</span>, <span class="tok-kt">JInteger</span><span class="tok-o">]])</span><span class="tok-k">:</span> <span class="tok-kt">Unit</span> <span class="tok-o">=</span> <span class="tok-o">{</span>
      <span class="tok-c1">// emit the value and rank</span>
      <span class="tok-k">if</span> <span class="tok-o">(</span><span class="tok-n">acc</span><span class="tok-o">.</span><span class="tok-n">first</span> <span class="tok-o">!=</span> <span class="tok-nc">Int</span><span class="tok-o">.</span><span class="tok-nc">MinValue</span><span class="tok-o">)</span> <span class="tok-o">{</span>
        <span class="tok-n">out</span><span class="tok-o">.</span><span class="tok-n">collect</span><span class="tok-o">(</span><span class="tok-nc">JTuple2</span><span class="tok-o">.</span><span class="tok-n">of</span><span class="tok-o">(</span><span class="tok-n">acc</span><span class="tok-o">.</span><span class="tok-n">first</span><span class="tok-o">,</span> <span class="tok-mi">1</span><span class="tok-o">))</span>
      <span class="tok-o">}</span>
      <span class="tok-k">if</span> <span class="tok-o">(</span><span class="tok-n">acc</span><span class="tok-o">.</span><span class="tok-n">second</span> <span class="tok-o">!=</span> <span class="tok-nc">Int</span><span class="tok-o">.</span><span class="tok-nc">MinValue</span><span class="tok-o">)</span> <span class="tok-o">{</span>
        <span class="tok-n">out</span><span class="tok-o">.</span><span class="tok-n">collect</span><span class="tok-o">(</span><span class="tok-nc">JTuple2</span><span class="tok-o">.</span><span class="tok-n">of</span><span class="tok-o">(</span><span class="tok-n">acc</span><span class="tok-o">.</span><span class="tok-n">second</span><span class="tok-o">,</span> <span class="tok-mi">2</span><span class="tok-o">))</span>
      <span class="tok-o">}</span>
    <span class="tok-o">}</span>
  <span class="tok-o">}</span>
<span class="tok-o">}</span></code></pre>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="sect1">
<h2 id="_尚硅谷大数据技术之电商用户行为分析">12. 尚硅谷大数据技术之电商用户行为分析</h2>
<div class="sectionbody">
<div class="sect2">
<h3 id="_数据集解析">12.1. 数据集解析</h3>
<div class="sect3">
<h4 id="_淘宝数据集解析">12.1.1. 淘宝数据集解析</h4>
<div class="paragraph">
<p>我们准备了一份淘宝用户行为数据集，保存为csv文件。本数据集包含了淘宝上某一天随机一百万用户的所有行为（包括点击、购买、收藏、喜欢）。数据集的每一行表示一条用户行为，由用户ID、商品ID、商品类目ID、行为类型和时间戳组成，并以逗号分隔。关于数据集中每一列的详细描述如下：</p>
</div>
<table class="tableblock frame-all grid-all stretch">
<colgroup>
<col style="width: 33.3333%;">
<col style="width: 33.3333%;">
<col style="width: 33.3334%;">
</colgroup>
<thead>
<tr>
<th class="tableblock halign-left valign-top">字段名</th>
<th class="tableblock halign-left valign-top">数据类型</th>
<th class="tableblock halign-left valign-top">说明</th>
</tr>
</thead>
<tbody>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock">userId</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">Long</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">加密后的用户ID</p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock">itemId</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">Long</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">加密后的商品ID</p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock">categoryId</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">Int</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">加密后的商品所属类别ID</p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock">behavior</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">String</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">用户行为类型，包括('pv', 'buy', 'cart', 'fav')</p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock">timestamp</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">Long</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">行为发生的时间戳，单位秒</p></td>
</tr>
</tbody>
</table>
</div>
<div class="sect3">
<h4 id="_apache服务器日志数据集解析">12.1.2. Apache服务器日志数据集解析</h4>
<div class="paragraph">
<p>这里以apache服务器的一份log为例，每一行日志记录了访问者的IP、userId、访问时间、访问方法以及访问的url，具体描述如下：</p>
</div>
<table class="tableblock frame-all grid-all stretch">
<colgroup>
<col style="width: 33.3333%;">
<col style="width: 33.3333%;">
<col style="width: 33.3334%;">
</colgroup>
<thead>
<tr>
<th class="tableblock halign-left valign-top">字段名</th>
<th class="tableblock halign-left valign-top">数据类型</th>
<th class="tableblock halign-left valign-top">说明</th>
</tr>
</thead>
<tbody>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock">ip</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">String</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">访问的IP</p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock">userId</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">Long</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">访问的user ID</p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock">eventTime</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">Long</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">访问时间</p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock">method</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">String</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">访问方法 GET/POST/PUT/DELETE</p></td>
</tr>
<tr>
<td class="tableblock halign-left valign-top"><p class="tableblock">url</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">String</p></td>
<td class="tableblock halign-left valign-top"><p class="tableblock">访问的url</p></td>
</tr>
</tbody>
</table>
</div>
</div>
<div class="sect2">
<h3 id="_实时热门商品统计">12.2. 实时热门商品统计</h3>
<div class="paragraph">
<p>首先要实现的是实时热门商品统计，我们将会基于UserBehavior数据集来进行分析。</p>
</div>
<div class="paragraph">
<p><strong>基本需求</strong></p>
</div>
<div class="ulist">
<ul>
<li>
<p>每隔5分钟输出最近一小时内点击量最多的前N个商品</p>
</li>
<li>
<p>点击量用浏览次数("pv")来衡量</p>
</li>
</ul>
</div>
<div class="paragraph">
<p><strong>解决思路</strong></p>
</div>
<div class="olist arabic">
<ol class="arabic">
<li>
<p>在所有用户行为数据中，过滤出浏览("pv")行为进行统计</p>
</li>
<li>
<p>构建滑动窗口，窗口长度为1小时，滑动距离为5分钟</p>
</li>
<li>
<p>窗口计算使用增量聚合函数和全窗口聚合函数相结合的方法</p>
</li>
<li>
<p>使用窗口结束时间作为key，对DataStream进行keyBy()操作</p>
</li>
<li>
<p>将KeyedStream中的元素存储到ListState中，当水位线超过窗口结束时间时，排序输出</p>
</li>
</ol>
</div>
<div class="paragraph">
<p><strong>数据准备</strong></p>
</div>
<div class="paragraph">
<p>将数据文件UserBehavior.csv复制到资源文件目录src/main/resources下。</p>
</div>
<div class="paragraph">
<p><strong>程序主体</strong></p>
</div>
<div class="listingblock">
<div class="title">HotItems.scala</div>
<div class="content">
<pre class="pygments highlight"><code data-lang="scala"><span></span><span class="tok-c1">// 把数据需要ETL成UserBehavior类型</span>
<span class="tok-k">case</span> <span class="tok-k">class</span> <span class="tok-nc">UserBehavior</span><span class="tok-o">(</span><span class="tok-n">userId</span><span class="tok-k">:</span> <span class="tok-kt">Long</span><span class="tok-o">,</span> <span class="tok-n">itemId</span><span class="tok-k">:</span> <span class="tok-kt">Long</span><span class="tok-o">,</span> <span class="tok-n">categoryId</span><span class="tok-k">:</span> <span class="tok-kt">Int</span><span class="tok-o">,</span> <span class="tok-n">behavior</span><span class="tok-k">:</span> <span class="tok-kt">String</span><span class="tok-o">,</span> <span class="tok-n">timestamp</span><span class="tok-k">:</span> <span class="tok-kt">Long</span><span class="tok-o">)</span>

<span class="tok-c1">// 全窗口聚合函数输出的数据类型</span>
<span class="tok-k">case</span> <span class="tok-k">class</span> <span class="tok-nc">ItemViewCount</span><span class="tok-o">(</span><span class="tok-n">itemId</span><span class="tok-k">:</span> <span class="tok-kt">Long</span><span class="tok-o">,</span> <span class="tok-n">windowEnd</span><span class="tok-k">:</span> <span class="tok-kt">Long</span><span class="tok-o">,</span> <span class="tok-n">count</span><span class="tok-k">:</span> <span class="tok-kt">Long</span><span class="tok-o">)</span>

<span class="tok-k">object</span> <span class="tok-nc">HotItems</span> <span class="tok-o">{</span>
  <span class="tok-k">def</span> <span class="tok-n">main</span><span class="tok-o">(</span><span class="tok-n">args</span><span class="tok-k">:</span> <span class="tok-kt">Array</span><span class="tok-o">[</span><span class="tok-kt">String</span><span class="tok-o">])</span><span class="tok-k">:</span> <span class="tok-kt">Unit</span> <span class="tok-o">=</span> <span class="tok-o">{</span>
    <span class="tok-c1">// 创建一个 StreamExecutionEnvironment</span>
    <span class="tok-k">val</span> <span class="tok-n">env</span> <span class="tok-k">=</span> <span class="tok-nc">StreamExecutionEnvironment</span><span class="tok-o">.</span><span class="tok-n">getExecutionEnvironment</span>
    <span class="tok-c1">// 设定Time类型为EventTime</span>
    <span class="tok-n">env</span><span class="tok-o">.</span><span class="tok-n">setStreamTimeCharacteristic</span><span class="tok-o">(</span><span class="tok-nc">TimeCharacteristic</span><span class="tok-o">.</span><span class="tok-nc">EventTime</span><span class="tok-o">)</span>
    <span class="tok-c1">// 为了打印到控制台的结果不乱序，我们配置全局的并发为1，这里改变并发对结果正确性没有影响</span>
    <span class="tok-n">env</span><span class="tok-o">.</span><span class="tok-n">setParallelism</span><span class="tok-o">(</span><span class="tok-mi">1</span><span class="tok-o">)</span>
    <span class="tok-k">val</span> <span class="tok-n">stream</span> <span class="tok-k">=</span> <span class="tok-n">env</span>
      <span class="tok-c1">// 以window下为例，需替换成数据集的绝对路径</span>
      <span class="tok-o">.</span><span class="tok-n">readTextFile</span><span class="tok-o">(</span><span class="tok-s">&quot;YOUR_PATH\\resources\\UserBehavior.csv&quot;</span><span class="tok-o">)</span>
      <span class="tok-o">.</span><span class="tok-n">map</span><span class="tok-o">(</span><span class="tok-n">line</span> <span class="tok-k">=&gt;</span> <span class="tok-o">{</span>
        <span class="tok-k">val</span> <span class="tok-n">linearray</span> <span class="tok-k">=</span> <span class="tok-n">line</span><span class="tok-o">.</span><span class="tok-n">split</span><span class="tok-o">(</span><span class="tok-s">&quot;,&quot;</span><span class="tok-o">)</span>
        <span class="tok-nc">UserBehavior</span><span class="tok-o">(</span><span class="tok-n">linearray</span><span class="tok-o">(</span><span class="tok-mi">0</span><span class="tok-o">).</span><span class="tok-n">toLong</span><span class="tok-o">,</span> <span class="tok-n">linearray</span><span class="tok-o">(</span><span class="tok-mi">1</span><span class="tok-o">).</span><span class="tok-n">toLong</span><span class="tok-o">,</span> <span class="tok-n">linearray</span><span class="tok-o">(</span><span class="tok-mi">2</span><span class="tok-o">).</span><span class="tok-n">toInt</span><span class="tok-o">,</span> <span class="tok-n">linearray</span><span class="tok-o">(</span><span class="tok-mi">3</span><span class="tok-o">),</span> <span class="tok-n">linearray</span><span class="tok-o">(</span><span class="tok-mi">4</span><span class="tok-o">).</span><span class="tok-n">toLong</span><span class="tok-o">)</span>
      <span class="tok-o">})</span>
      <span class="tok-c1">// 过滤出点击事件</span>
      <span class="tok-o">.</span><span class="tok-n">filter</span><span class="tok-o">(</span><span class="tok-k">_</span><span class="tok-o">.</span><span class="tok-n">behavior</span> <span class="tok-o">==</span> <span class="tok-s">&quot;pv&quot;</span><span class="tok-o">)</span>
      <span class="tok-c1">// 指定时间戳和Watermark，这里我们已经知道了数据集的时间戳是单调递增的了。</span>
      <span class="tok-o">.</span><span class="tok-n">assignAscendingTimestamps</span><span class="tok-o">(</span><span class="tok-k">_</span><span class="tok-o">.</span><span class="tok-n">timestamp</span> <span class="tok-o">*</span> <span class="tok-mi">1000</span><span class="tok-o">)</span>
      <span class="tok-c1">// 根据商品Id分流</span>
      <span class="tok-o">.</span><span class="tok-n">keyBy</span><span class="tok-o">(</span><span class="tok-k">_</span><span class="tok-o">.</span><span class="tok-n">itemId</span><span class="tok-o">)</span>
      <span class="tok-c1">// 开窗操作</span>
      <span class="tok-o">.</span><span class="tok-n">timeWindow</span><span class="tok-o">(</span><span class="tok-nc">Time</span><span class="tok-o">.</span><span class="tok-n">minutes</span><span class="tok-o">(</span><span class="tok-mi">60</span><span class="tok-o">),</span> <span class="tok-nc">Time</span><span class="tok-o">.</span><span class="tok-n">minutes</span><span class="tok-o">(</span><span class="tok-mi">5</span><span class="tok-o">))</span>
      <span class="tok-c1">// 窗口计算操作</span>
      <span class="tok-o">.</span><span class="tok-n">aggregate</span><span class="tok-o">(</span><span class="tok-k">new</span> <span class="tok-nc">CountAgg</span><span class="tok-o">(),</span> <span class="tok-k">new</span> <span class="tok-nc">WindowResultFunction</span><span class="tok-o">())</span>
      <span class="tok-c1">// 根据窗口结束时间分流</span>
      <span class="tok-o">.</span><span class="tok-n">keyBy</span><span class="tok-o">(</span><span class="tok-k">_</span><span class="tok-o">.</span><span class="tok-n">windowEnd</span><span class="tok-o">)</span>
      <span class="tok-c1">// 求点击量前3名的商品</span>
      <span class="tok-o">.</span><span class="tok-n">process</span><span class="tok-o">(</span><span class="tok-k">new</span> <span class="tok-nc">TopNHotItems</span><span class="tok-o">(</span><span class="tok-mi">3</span><span class="tok-o">))</span>

    <span class="tok-c1">// 打印结果</span>
    <span class="tok-n">stream</span><span class="tok-o">.</span><span class="tok-n">print</span><span class="tok-o">()</span>

    <span class="tok-c1">// 别忘了执行</span>
    <span class="tok-n">env</span><span class="tok-o">.</span><span class="tok-n">execute</span><span class="tok-o">(</span><span class="tok-s">&quot;Hot Items Job&quot;</span><span class="tok-o">)</span>
  <span class="tok-o">}</span>
<span class="tok-o">}</span></code></pre>
</div>
</div>
<div class="admonitionblock note">
<table>
<tr>
<td class="icon">
<i class="fa icon-note" title="Note"></i>
</td>
<td class="content">
真实业务场景一般都是乱序的，所以一般不用<code>assignAscendingTimestamps</code>，而是使用<code>BoundedOutOfOrdernessTimestampExtractor</code>。
</td>
</tr>
</table>
</div>
<div class="paragraph">
<p><strong>增量聚合函数逻辑编写</strong></p>
</div>
<div class="listingblock">
<div class="content">
<pre class="pygments highlight"><code data-lang="scala"><span></span><span class="tok-c1">// COUNT统计的聚合函数实现，每出现一条记录就加一</span>
<span class="tok-k">class</span> <span class="tok-nc">CountAgg</span> <span class="tok-k">extends</span> <span class="tok-nc">AggregateFunction</span><span class="tok-o">[</span><span class="tok-kt">UserBehavior</span>, <span class="tok-kt">Long</span>, <span class="tok-kt">Long</span><span class="tok-o">]</span> <span class="tok-o">{</span>
  <span class="tok-k">override</span> <span class="tok-k">def</span> <span class="tok-n">createAccumulator</span><span class="tok-o">()</span><span class="tok-k">:</span> <span class="tok-kt">Long</span> <span class="tok-o">=</span> <span class="tok-mi">0L</span>
  <span class="tok-k">override</span> <span class="tok-k">def</span> <span class="tok-n">add</span><span class="tok-o">(</span><span class="tok-n">userBehavior</span><span class="tok-k">:</span> <span class="tok-kt">UserBehavior</span><span class="tok-o">,</span> <span class="tok-n">acc</span><span class="tok-k">:</span> <span class="tok-kt">Long</span><span class="tok-o">)</span><span class="tok-k">:</span> <span class="tok-kt">Long</span> <span class="tok-o">=</span> <span class="tok-n">acc</span> <span class="tok-o">+</span> <span class="tok-mi">1</span>
  <span class="tok-k">override</span> <span class="tok-k">def</span> <span class="tok-n">getResult</span><span class="tok-o">(</span><span class="tok-n">acc</span><span class="tok-k">:</span> <span class="tok-kt">Long</span><span class="tok-o">)</span><span class="tok-k">:</span> <span class="tok-kt">Long</span> <span class="tok-o">=</span> <span class="tok-n">acc</span>
  <span class="tok-k">override</span> <span class="tok-k">def</span> <span class="tok-n">merge</span><span class="tok-o">(</span><span class="tok-n">acc1</span><span class="tok-k">:</span> <span class="tok-kt">Long</span><span class="tok-o">,</span> <span class="tok-n">acc2</span><span class="tok-k">:</span> <span class="tok-kt">Long</span><span class="tok-o">)</span><span class="tok-k">:</span> <span class="tok-kt">Long</span> <span class="tok-o">=</span> <span class="tok-n">acc1</span> <span class="tok-o">+</span> <span class="tok-n">acc2</span>
<span class="tok-o">}</span></code></pre>
</div>
</div>
<div class="paragraph">
<p><strong>全窗口聚合函数逻辑编写</strong></p>
</div>
<div class="paragraph">
<p>其实就是将增量聚合的结果包上一层窗口信息和key的信息。</p>
</div>
<div class="paragraph">
<p>代码如下：</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="pygments highlight"><code data-lang="scala"><span></span><span class="tok-c1">// 用于输出窗口的结果</span>
<span class="tok-k">class</span> <span class="tok-nc">WindowResultFunction</span> <span class="tok-k">extends</span> <span class="tok-nc">ProcessWindowFunction</span><span class="tok-o">[</span><span class="tok-kt">Long</span>, <span class="tok-kt">ItemViewCount</span>, <span class="tok-kt">String</span>, <span class="tok-kt">TimeWindow</span><span class="tok-o">]</span> <span class="tok-o">{</span>
  <span class="tok-k">override</span> <span class="tok-k">def</span> <span class="tok-n">process</span><span class="tok-o">(</span><span class="tok-n">key</span><span class="tok-k">:</span> <span class="tok-kt">String</span><span class="tok-o">,</span>
                        <span class="tok-n">context</span><span class="tok-k">:</span> <span class="tok-kt">Context</span><span class="tok-o">,</span>
                        <span class="tok-n">elements</span><span class="tok-k">:</span> <span class="tok-kt">Iterable</span><span class="tok-o">[</span><span class="tok-kt">Long</span><span class="tok-o">],</span>
                        <span class="tok-n">out</span><span class="tok-k">:</span> <span class="tok-kt">Collector</span><span class="tok-o">[</span><span class="tok-kt">ItemViewCount</span><span class="tok-o">])</span><span class="tok-k">:</span> <span class="tok-kt">Unit</span> <span class="tok-o">=</span> <span class="tok-o">{</span>
    <span class="tok-n">out</span><span class="tok-o">.</span><span class="tok-n">collect</span><span class="tok-o">(</span><span class="tok-nc">ItemViewCount</span><span class="tok-o">(</span><span class="tok-n">key</span><span class="tok-o">,</span> <span class="tok-n">context</span><span class="tok-o">.</span><span class="tok-n">window</span><span class="tok-o">.</span><span class="tok-n">getEnd</span><span class="tok-o">,</span> <span class="tok-n">elements</span><span class="tok-o">.</span><span class="tok-n">iterator</span><span class="tok-o">.</span><span class="tok-n">next</span><span class="tok-o">()))</span>
  <span class="tok-o">}</span>
<span class="tok-o">}</span></code></pre>
</div>
</div>
<div class="paragraph">
<p>现在我们就得到了每个商品在每个窗口的点击量的数据流。</p>
</div>
<div class="paragraph">
<p><strong>计算最热门TopN商品</strong></p>
</div>
<div class="listingblock">
<div class="content">
<pre class="pygments highlight"><code data-lang="scala"><span></span>  <span class="tok-k">class</span> <span class="tok-nc">TopNHotItems</span><span class="tok-o">(</span><span class="tok-n">topSize</span><span class="tok-k">:</span> <span class="tok-kt">Int</span><span class="tok-o">)</span> <span class="tok-k">extends</span> <span class="tok-nc">KeyedProcessFunction</span><span class="tok-o">[</span><span class="tok-kt">Long</span>, <span class="tok-kt">ItemViewCount</span>, <span class="tok-kt">String</span><span class="tok-o">]</span> <span class="tok-o">{</span>
    <span class="tok-c1">// 惰性赋值一个状态变量</span>
    <span class="tok-k">lazy</span> <span class="tok-k">val</span> <span class="tok-n">itemState</span> <span class="tok-k">=</span> <span class="tok-n">getRuntimeContext</span><span class="tok-o">.</span><span class="tok-n">getListState</span><span class="tok-o">(</span>
      <span class="tok-k">new</span> <span class="tok-nc">ListStateDescriptor</span><span class="tok-o">[</span><span class="tok-kt">ItemViewCount</span><span class="tok-o">](</span><span class="tok-s">&quot;items&quot;</span><span class="tok-o">,</span> <span class="tok-nc">Types</span><span class="tok-o">.</span><span class="tok-n">of</span><span class="tok-o">[</span><span class="tok-kt">ItemViewCount</span><span class="tok-o">])</span>
    <span class="tok-o">)</span>

    <span class="tok-c1">// 来一条数据都会调用一次</span>
    <span class="tok-k">override</span> <span class="tok-k">def</span> <span class="tok-n">processElement</span><span class="tok-o">(</span><span class="tok-n">value</span><span class="tok-k">:</span> <span class="tok-kt">ItemViewCount</span><span class="tok-o">,</span>
                                <span class="tok-n">ctx</span><span class="tok-k">:</span> <span class="tok-kt">KeyedProcessFunction</span><span class="tok-o">[</span><span class="tok-kt">Long</span>, <span class="tok-kt">ItemViewCount</span>, <span class="tok-kt">String</span><span class="tok-o">]</span><span class="tok-k">#</span><span class="tok-nc">Context</span><span class="tok-o">,</span>
                                <span class="tok-n">out</span><span class="tok-k">:</span> <span class="tok-kt">Collector</span><span class="tok-o">[</span><span class="tok-kt">String</span><span class="tok-o">])</span><span class="tok-k">:</span> <span class="tok-kt">Unit</span> <span class="tok-o">=</span> <span class="tok-o">{</span>
      <span class="tok-n">itemState</span><span class="tok-o">.</span><span class="tok-n">add</span><span class="tok-o">(</span><span class="tok-n">value</span><span class="tok-o">)</span>
      <span class="tok-n">ctx</span><span class="tok-o">.</span><span class="tok-n">timerService</span><span class="tok-o">().</span><span class="tok-n">registerEventTimeTimer</span><span class="tok-o">(</span><span class="tok-n">value</span><span class="tok-o">.</span><span class="tok-n">windowEnd</span> <span class="tok-o">+</span> <span class="tok-mi">1</span><span class="tok-o">)</span>
    <span class="tok-o">}</span>

    <span class="tok-c1">// 定时器事件</span>
    <span class="tok-k">override</span> <span class="tok-k">def</span> <span class="tok-n">onTimer</span><span class="tok-o">(</span><span class="tok-n">ts</span><span class="tok-k">:</span> <span class="tok-kt">Long</span><span class="tok-o">,</span>
                         <span class="tok-n">ctx</span><span class="tok-k">:</span> <span class="tok-kt">KeyedProcessFunction</span><span class="tok-o">[</span><span class="tok-kt">Long</span>, <span class="tok-kt">ItemViewCount</span>, <span class="tok-kt">String</span><span class="tok-o">]</span><span class="tok-k">#</span><span class="tok-nc">OnTimerContext</span><span class="tok-o">,</span>
                         <span class="tok-n">out</span><span class="tok-k">:</span> <span class="tok-kt">Collector</span><span class="tok-o">[</span><span class="tok-kt">String</span><span class="tok-o">])</span><span class="tok-k">:</span> <span class="tok-kt">Unit</span> <span class="tok-o">=</span> <span class="tok-o">{</span>
      <span class="tok-k">val</span> <span class="tok-n">allItems</span><span class="tok-k">:</span> <span class="tok-kt">ListBuffer</span><span class="tok-o">[</span><span class="tok-kt">ItemViewCount</span><span class="tok-o">]</span> <span class="tok-k">=</span> <span class="tok-nc">ListBuffer</span><span class="tok-o">()</span>
      <span class="tok-c1">// 导入一些隐式类型转换</span>
      <span class="tok-k">import</span> <span class="tok-nn">scala.collection.JavaConversions._</span>
      <span class="tok-k">for</span> <span class="tok-o">(</span><span class="tok-n">item</span> <span class="tok-k">&lt;-</span> <span class="tok-n">itemState</span><span class="tok-o">.</span><span class="tok-n">get</span><span class="tok-o">)</span> <span class="tok-o">{</span>
        <span class="tok-n">allItems</span> <span class="tok-o">+=</span> <span class="tok-n">item</span>
      <span class="tok-o">}</span>

      <span class="tok-c1">// 清空状态变量，释放空间</span>
      <span class="tok-n">itemState</span><span class="tok-o">.</span><span class="tok-n">clear</span><span class="tok-o">()</span>

      <span class="tok-c1">// 降序排列</span>
      <span class="tok-k">val</span> <span class="tok-n">sortedItems</span> <span class="tok-k">=</span> <span class="tok-n">allItems</span><span class="tok-o">.</span><span class="tok-n">sortBy</span><span class="tok-o">(-</span><span class="tok-k">_</span><span class="tok-o">.</span><span class="tok-n">count</span><span class="tok-o">).</span><span class="tok-n">take</span><span class="tok-o">(</span><span class="tok-n">topSize</span><span class="tok-o">)</span>
      <span class="tok-k">val</span> <span class="tok-n">result</span> <span class="tok-k">=</span> <span class="tok-k">new</span> <span class="tok-nc">StringBuilder</span>
      <span class="tok-n">result</span><span class="tok-o">.</span><span class="tok-n">append</span><span class="tok-o">(</span><span class="tok-s">&quot;====================================\n&quot;</span><span class="tok-o">)</span>
      <span class="tok-n">result</span><span class="tok-o">.</span><span class="tok-n">append</span><span class="tok-o">(</span><span class="tok-s">&quot;时间: &quot;</span><span class="tok-o">).</span><span class="tok-n">append</span><span class="tok-o">(</span><span class="tok-k">new</span> <span class="tok-nc">Timestamp</span><span class="tok-o">(</span><span class="tok-n">ts</span> <span class="tok-o">-</span> <span class="tok-mi">1</span><span class="tok-o">)).</span><span class="tok-n">append</span><span class="tok-o">(</span><span class="tok-s">&quot;\n&quot;</span><span class="tok-o">)</span>
      <span class="tok-k">for</span> <span class="tok-o">(</span><span class="tok-n">i</span> <span class="tok-k">&lt;-</span> <span class="tok-n">sortedItems</span><span class="tok-o">.</span><span class="tok-n">indices</span><span class="tok-o">)</span> <span class="tok-o">{</span>
        <span class="tok-k">val</span> <span class="tok-n">currentItem</span> <span class="tok-k">=</span> <span class="tok-n">sortedItems</span><span class="tok-o">(</span><span class="tok-n">i</span><span class="tok-o">)</span>
        <span class="tok-n">result</span><span class="tok-o">.</span><span class="tok-n">append</span><span class="tok-o">(</span><span class="tok-s">&quot;No&quot;</span><span class="tok-o">)</span>
          <span class="tok-o">.</span><span class="tok-n">append</span><span class="tok-o">(</span><span class="tok-n">i</span><span class="tok-o">+</span><span class="tok-mi">1</span><span class="tok-o">)</span>
          <span class="tok-o">.</span><span class="tok-n">append</span><span class="tok-o">(</span><span class="tok-s">&quot;:&quot;</span><span class="tok-o">)</span>
          <span class="tok-o">.</span><span class="tok-n">append</span><span class="tok-o">(</span><span class="tok-s">&quot;  商品ID=&quot;</span><span class="tok-o">)</span>
          <span class="tok-o">.</span><span class="tok-n">append</span><span class="tok-o">(</span><span class="tok-n">currentItem</span><span class="tok-o">.</span><span class="tok-n">itemId</span><span class="tok-o">)</span>
          <span class="tok-o">.</span><span class="tok-n">append</span><span class="tok-o">(</span><span class="tok-s">&quot;  浏览量=&quot;</span><span class="tok-o">)</span>
          <span class="tok-o">.</span><span class="tok-n">append</span><span class="tok-o">(</span><span class="tok-n">currentItem</span><span class="tok-o">.</span><span class="tok-n">count</span><span class="tok-o">)</span>
          <span class="tok-o">.</span><span class="tok-n">append</span><span class="tok-o">(</span><span class="tok-s">&quot;\n&quot;</span><span class="tok-o">)</span>
      <span class="tok-o">}</span>
      <span class="tok-n">result</span><span class="tok-o">.</span><span class="tok-n">append</span><span class="tok-o">(</span><span class="tok-s">&quot;====================================\n\n&quot;</span><span class="tok-o">)</span>
      <span class="tok-nc">Thread</span><span class="tok-o">.</span><span class="tok-n">sleep</span><span class="tok-o">(</span><span class="tok-mi">1000</span><span class="tok-o">)</span>
      <span class="tok-n">out</span><span class="tok-o">.</span><span class="tok-n">collect</span><span class="tok-o">(</span><span class="tok-n">result</span><span class="tok-o">.</span><span class="tok-n">toString</span><span class="tok-o">())</span>
    <span class="tok-o">}</span>
  <span class="tok-o">}</span></code></pre>
</div>
</div>
<div class="paragraph">
<p><strong>更换Kafka作为数据源</strong></p>
</div>
<div class="paragraph">
<p>实际生产环境中，我们的数据流往往是从Kafka获取到的。如果要让代码更贴近生产实际，我们只需将source更换为Kafka即可：</p>
</div>
<div class="admonitionblock note">
<table>
<tr>
<td class="icon">
<i class="fa icon-note" title="Note"></i>
</td>
<td class="content">
注意：这里Kafka的版本要用2.2！
</td>
</tr>
</table>
</div>
<div class="paragraph">
<p>添加依赖：</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="pygments highlight"><code data-lang="xml"><span></span><span class="tok-nt">&lt;dependency&gt;</span>
  <span class="tok-nt">&lt;groupId&gt;</span>org.apache.flink<span class="tok-nt">&lt;/groupId&gt;</span>
  <span class="tok-nt">&lt;artifactId&gt;</span>flink-connector-kafka_${scala.binary.version}<span class="tok-nt">&lt;/artifactId&gt;</span>
  <span class="tok-nt">&lt;version&gt;</span>${flink.version}<span class="tok-nt">&lt;/version&gt;</span>
<span class="tok-nt">&lt;/dependency&gt;</span></code></pre>
</div>
</div>
<div class="paragraph">
<p>编写代码：</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="pygments highlight"><code data-lang="scala"><span></span><span class="tok-k">val</span> <span class="tok-n">properties</span> <span class="tok-k">=</span> <span class="tok-k">new</span> <span class="tok-nc">Properties</span><span class="tok-o">()</span>
<span class="tok-n">properties</span><span class="tok-o">.</span><span class="tok-n">setProperty</span><span class="tok-o">(</span><span class="tok-s">&quot;bootstrap.servers&quot;</span><span class="tok-o">,</span> <span class="tok-s">&quot;localhost:9092&quot;</span><span class="tok-o">)</span>
<span class="tok-n">properties</span><span class="tok-o">.</span><span class="tok-n">setProperty</span><span class="tok-o">(</span><span class="tok-s">&quot;group.id&quot;</span><span class="tok-o">,</span> <span class="tok-s">&quot;consumer-group&quot;</span><span class="tok-o">)</span>
<span class="tok-n">properties</span><span class="tok-o">.</span><span class="tok-n">setProperty</span><span class="tok-o">(</span><span class="tok-s">&quot;key.deserializer&quot;</span><span class="tok-o">,</span> <span class="tok-s">&quot;org.apache.kafka.common.serialization.StringDeserializer&quot;</span><span class="tok-o">)</span>
<span class="tok-n">properties</span><span class="tok-o">.</span><span class="tok-n">setProperty</span><span class="tok-o">(</span><span class="tok-s">&quot;value.deserializer&quot;</span><span class="tok-o">,</span>
<span class="tok-s">&quot;org.apache.kafka.common.serialization.StringDeserializer&quot;</span><span class="tok-o">)</span>
<span class="tok-n">properties</span><span class="tok-o">.</span><span class="tok-n">setProperty</span><span class="tok-o">(</span><span class="tok-s">&quot;auto.offset.reset&quot;</span><span class="tok-o">,</span> <span class="tok-s">&quot;latest&quot;</span><span class="tok-o">)</span>

<span class="tok-k">val</span> <span class="tok-n">env</span> <span class="tok-k">=</span> <span class="tok-nc">StreamExecutionEnvironment</span><span class="tok-o">.</span><span class="tok-n">getExecutionEnvironment</span>
<span class="tok-n">env</span><span class="tok-o">.</span><span class="tok-n">setStreamTimeCharacteristic</span><span class="tok-o">(</span><span class="tok-nc">TimeCharacteristic</span><span class="tok-o">.</span><span class="tok-nc">EventTime</span><span class="tok-o">)</span>
<span class="tok-n">env</span><span class="tok-o">.</span><span class="tok-n">setParallelism</span><span class="tok-o">(</span><span class="tok-mi">1</span><span class="tok-o">)</span>

<span class="tok-k">val</span> <span class="tok-n">stream</span> <span class="tok-k">=</span> <span class="tok-n">env</span>
  <span class="tok-o">.</span><span class="tok-n">addSource</span><span class="tok-o">(</span><span class="tok-k">new</span> <span class="tok-nc">FlinkKafkaConsumer</span><span class="tok-o">[</span><span class="tok-kt">String</span><span class="tok-o">](</span><span class="tok-s">&quot;hotitems&quot;</span><span class="tok-o">,</span> <span class="tok-k">new</span> <span class="tok-nc">SimpleStringSchema</span><span class="tok-o">(),</span> <span class="tok-n">properties</span><span class="tok-o">))</span></code></pre>
</div>
</div>
<div class="paragraph">
<p>当然，根据实际的需要，我们还可以将Sink指定为Kafka、ES、Redis或其它存储，这里就不一一展开实现了。</p>
</div>
<div class="paragraph">
<p><strong>kafka生产者程序</strong></p>
</div>
<div class="paragraph">
<p>添加依赖</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="pygments highlight"><code data-lang="xml"><span></span><span class="tok-nt">&lt;dependency&gt;</span>
    <span class="tok-nt">&lt;groupId&gt;</span>org.apache.kafka<span class="tok-nt">&lt;/groupId&gt;</span>
    <span class="tok-nt">&lt;artifactId&gt;</span>kafka_2.11<span class="tok-nt">&lt;/artifactId&gt;</span>
    <span class="tok-nt">&lt;version&gt;</span>2.2.0<span class="tok-nt">&lt;/version&gt;</span>
<span class="tok-nt">&lt;/dependency&gt;</span></code></pre>
</div>
</div>
<div class="paragraph">
<p>编写代码：</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="pygments highlight"><code data-lang="scala"><span></span><span class="tok-k">import</span> <span class="tok-nn">java.util.Properties</span>
<span class="tok-k">import</span> <span class="tok-nn">org.apache.kafka.clients.producer.</span><span class="tok-o">{</span><span class="tok-nc">KafkaProducer</span><span class="tok-o">,</span> <span class="tok-nc">ProducerRecord</span><span class="tok-o">}</span>

<span class="tok-k">object</span> <span class="tok-nc">KafkaProducerUtil</span> <span class="tok-o">{</span>

  <span class="tok-k">def</span> <span class="tok-n">main</span><span class="tok-o">(</span><span class="tok-n">args</span><span class="tok-k">:</span> <span class="tok-kt">Array</span><span class="tok-o">[</span><span class="tok-kt">String</span><span class="tok-o">])</span><span class="tok-k">:</span> <span class="tok-kt">Unit</span> <span class="tok-o">=</span> <span class="tok-o">{</span>
    <span class="tok-n">writeToKafka</span><span class="tok-o">(</span><span class="tok-s">&quot;hotitems&quot;</span><span class="tok-o">)</span>
  <span class="tok-o">}</span>

  <span class="tok-k">def</span> <span class="tok-n">writeToKafka</span><span class="tok-o">(</span><span class="tok-n">topic</span><span class="tok-k">:</span> <span class="tok-kt">String</span><span class="tok-o">)</span><span class="tok-k">:</span> <span class="tok-kt">Unit</span> <span class="tok-o">=</span> <span class="tok-o">{</span>
    <span class="tok-k">val</span> <span class="tok-n">props</span> <span class="tok-k">=</span> <span class="tok-k">new</span> <span class="tok-nc">Properties</span><span class="tok-o">()</span>
    <span class="tok-n">props</span><span class="tok-o">.</span><span class="tok-n">put</span><span class="tok-o">(</span><span class="tok-s">&quot;bootstrap.servers&quot;</span><span class="tok-o">,</span> <span class="tok-s">&quot;localhost:9092&quot;</span><span class="tok-o">)</span>
    <span class="tok-n">props</span><span class="tok-o">.</span><span class="tok-n">put</span><span class="tok-o">(</span><span class="tok-s">&quot;key.serializer&quot;</span><span class="tok-o">,</span> <span class="tok-s">&quot;org.apache.kafka.common.serialization.StringSerializer&quot;</span><span class="tok-o">)</span>
    <span class="tok-n">props</span><span class="tok-o">.</span><span class="tok-n">put</span><span class="tok-o">(</span><span class="tok-s">&quot;value.serializer&quot;</span><span class="tok-o">,</span> <span class="tok-s">&quot;org.apache.kafka.common.serialization.StringSerializer&quot;</span><span class="tok-o">)</span>
    <span class="tok-k">val</span> <span class="tok-n">producer</span> <span class="tok-k">=</span> <span class="tok-k">new</span> <span class="tok-nc">KafkaProducer</span><span class="tok-o">[</span><span class="tok-kt">String</span>, <span class="tok-kt">String</span><span class="tok-o">](</span><span class="tok-n">props</span><span class="tok-o">)</span>
    <span class="tok-k">val</span> <span class="tok-n">bufferedSource</span> <span class="tok-k">=</span> <span class="tok-n">io</span><span class="tok-o">.</span><span class="tok-nc">Source</span><span class="tok-o">.</span><span class="tok-n">fromFile</span><span class="tok-o">(</span><span class="tok-s">&quot;UserBehavior.csv文件的绝对路径&quot;</span><span class="tok-o">)</span>
    <span class="tok-k">for</span> <span class="tok-o">(</span><span class="tok-n">line</span> <span class="tok-k">&lt;-</span> <span class="tok-n">bufferedSource</span><span class="tok-o">.</span><span class="tok-n">getLines</span><span class="tok-o">)</span> <span class="tok-o">{</span>
      <span class="tok-k">val</span> <span class="tok-n">record</span> <span class="tok-k">=</span> <span class="tok-k">new</span> <span class="tok-nc">ProducerRecord</span><span class="tok-o">[</span><span class="tok-kt">String</span>, <span class="tok-kt">String</span><span class="tok-o">](</span><span class="tok-n">topic</span><span class="tok-o">,</span> <span class="tok-n">line</span><span class="tok-o">)</span>
      <span class="tok-n">producer</span><span class="tok-o">.</span><span class="tok-n">send</span><span class="tok-o">(</span><span class="tok-n">record</span><span class="tok-o">)</span>
    <span class="tok-o">}</span>
    <span class="tok-n">producer</span><span class="tok-o">.</span><span class="tok-n">close</span><span class="tok-o">()</span>
  <span class="tok-o">}</span>
<span class="tok-o">}</span></code></pre>
</div>
</div>
</div>
<div class="sect2">
<h3 id="_实时流量统计">12.3. 实时流量统计</h3>
<div class="ulist">
<ul>
<li>
<p>基本需求</p>
<div class="ulist">
<ul>
<li>
<p>从web服务器的日志中，统计实时的访问流量</p>
</li>
<li>
<p>统计每分钟的ip访问量，取出访问量最大的5个地址，每5秒更新一次</p>
</li>
</ul>
</div>
</li>
<li>
<p>解决思路</p>
<div class="ulist">
<ul>
<li>
<p>将apache服务器日志中的时间，转换为时间戳，作为Event Time</p>
</li>
<li>
<p>构建滑动窗口，窗口长度为1分钟，滑动距离为5秒</p>
</li>
</ul>
</div>
</li>
</ul>
</div>
<div class="paragraph">
<p><strong>数据准备</strong></p>
</div>
<div class="paragraph">
<p>将apache服务器的日志文件apache.log复制到资源文件目录src/main/resources下，我们将从这里读取数据。</p>
</div>
<div class="paragraph">
<p><strong>代码实现</strong></p>
</div>
<div class="paragraph">
<p>我们现在要实现的模块是“实时流量统计”。对于一个电商平台而言，用户登录的入口流量、不同页面的访问流量都是值得分析的重要数据，而这些数据，可以简单地从web服务器的日志中提取出来。我们在这里实现最基本的“页面浏览数”的统计，也就是读取服务器日志中的每一行log，统计在一段时间内用户访问url的次数。</p>
</div>
<div class="paragraph">
<p>具体做法为：每隔5秒，输出最近10分钟内访问量最多的前N个URL。可以看出，这个需求与之前“实时热门商品统计”非常类似，所以我们完全可以借鉴此前的代码。</p>
</div>
<div class="paragraph">
<p>完整代码如下：</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="pygments highlight"><code data-lang="scala"><span></span><span class="tok-k">package</span> <span class="tok-nn">com.atguigu.project</span>

<span class="tok-k">import</span> <span class="tok-nn">java.sql.Timestamp</span>
<span class="tok-k">import</span> <span class="tok-nn">java.text.SimpleDateFormat</span>

<span class="tok-k">import</span> <span class="tok-nn">org.apache.flink.api.common.functions.AggregateFunction</span>
<span class="tok-k">import</span> <span class="tok-nn">org.apache.flink.api.common.state.ListStateDescriptor</span>
<span class="tok-k">import</span> <span class="tok-nn">org.apache.flink.api.scala.typeutils.Types</span>
<span class="tok-k">import</span> <span class="tok-nn">org.apache.flink.streaming.api.TimeCharacteristic</span>
<span class="tok-k">import</span> <span class="tok-nn">org.apache.flink.streaming.api.functions.KeyedProcessFunction</span>
<span class="tok-k">import</span> <span class="tok-nn">org.apache.flink.streaming.api.functions.timestamps.BoundedOutOfOrdernessTimestampExtractor</span>
<span class="tok-k">import</span> <span class="tok-nn">org.apache.flink.streaming.api.scala._</span>
<span class="tok-k">import</span> <span class="tok-nn">org.apache.flink.streaming.api.scala.function.ProcessWindowFunction</span>
<span class="tok-k">import</span> <span class="tok-nn">org.apache.flink.streaming.api.windowing.time.Time</span>
<span class="tok-k">import</span> <span class="tok-nn">org.apache.flink.streaming.api.windowing.windows.TimeWindow</span>
<span class="tok-k">import</span> <span class="tok-nn">org.apache.flink.util.Collector</span>

<span class="tok-k">import</span> <span class="tok-nn">scala.collection.mutable.ListBuffer</span>

<span class="tok-k">object</span> <span class="tok-nc">ApacheLogAnalysis</span> <span class="tok-o">{</span>

  <span class="tok-k">case</span> <span class="tok-k">class</span> <span class="tok-nc">ApacheLogEvent</span><span class="tok-o">(</span><span class="tok-n">ip</span><span class="tok-k">:</span> <span class="tok-kt">String</span><span class="tok-o">,</span> <span class="tok-n">userId</span><span class="tok-k">:</span> <span class="tok-kt">String</span><span class="tok-o">,</span> <span class="tok-n">eventTime</span><span class="tok-k">:</span> <span class="tok-kt">Long</span><span class="tok-o">,</span> <span class="tok-n">method</span><span class="tok-k">:</span> <span class="tok-kt">String</span><span class="tok-o">,</span> <span class="tok-n">url</span><span class="tok-k">:</span> <span class="tok-kt">String</span><span class="tok-o">)</span>

  <span class="tok-k">case</span> <span class="tok-k">class</span> <span class="tok-nc">UrlViewCount</span><span class="tok-o">(</span><span class="tok-n">url</span><span class="tok-k">:</span> <span class="tok-kt">String</span><span class="tok-o">,</span> <span class="tok-n">windowEnd</span><span class="tok-k">:</span> <span class="tok-kt">Long</span><span class="tok-o">,</span> <span class="tok-n">count</span><span class="tok-k">:</span> <span class="tok-kt">Long</span><span class="tok-o">)</span>

  <span class="tok-k">def</span> <span class="tok-n">main</span><span class="tok-o">(</span><span class="tok-n">args</span><span class="tok-k">:</span> <span class="tok-kt">Array</span><span class="tok-o">[</span><span class="tok-kt">String</span><span class="tok-o">])</span><span class="tok-k">:</span> <span class="tok-kt">Unit</span> <span class="tok-o">=</span> <span class="tok-o">{</span>
    <span class="tok-k">val</span> <span class="tok-n">env</span> <span class="tok-k">=</span> <span class="tok-nc">StreamExecutionEnvironment</span><span class="tok-o">.</span><span class="tok-n">getExecutionEnvironment</span>
    <span class="tok-n">env</span><span class="tok-o">.</span><span class="tok-n">setStreamTimeCharacteristic</span><span class="tok-o">(</span><span class="tok-nc">TimeCharacteristic</span><span class="tok-o">.</span><span class="tok-nc">EventTime</span><span class="tok-o">)</span>
    <span class="tok-n">env</span><span class="tok-o">.</span><span class="tok-n">setParallelism</span><span class="tok-o">(</span><span class="tok-mi">1</span><span class="tok-o">)</span>
    <span class="tok-k">val</span> <span class="tok-n">stream</span> <span class="tok-k">=</span> <span class="tok-n">env</span>
      <span class="tok-c1">// 文件的绝对路径</span>
      <span class="tok-o">.</span><span class="tok-n">readTextFile</span><span class="tok-o">(</span><span class="tok-s">&quot;YOUR_PATH\\resources\\apache.log&quot;</span><span class="tok-o">)</span>
      <span class="tok-o">.</span><span class="tok-n">map</span><span class="tok-o">(</span><span class="tok-n">line</span> <span class="tok-k">=&gt;</span> <span class="tok-o">{</span>
        <span class="tok-k">val</span> <span class="tok-n">linearray</span> <span class="tok-k">=</span> <span class="tok-n">line</span><span class="tok-o">.</span><span class="tok-n">split</span><span class="tok-o">(</span><span class="tok-s">&quot; &quot;</span><span class="tok-o">)</span>
        <span class="tok-c1">// 把时间戳ETL成毫秒</span>
        <span class="tok-k">val</span> <span class="tok-n">simpleDateFormat</span> <span class="tok-k">=</span> <span class="tok-k">new</span> <span class="tok-nc">SimpleDateFormat</span><span class="tok-o">(</span><span class="tok-s">&quot;dd/MM/yyyy:HH:mm:ss&quot;</span><span class="tok-o">)</span>
        <span class="tok-k">val</span> <span class="tok-n">timestamp</span> <span class="tok-k">=</span> <span class="tok-n">simpleDateFormat</span><span class="tok-o">.</span><span class="tok-n">parse</span><span class="tok-o">(</span><span class="tok-n">linearray</span><span class="tok-o">(</span><span class="tok-mi">3</span><span class="tok-o">)).</span><span class="tok-n">getTime</span>
        <span class="tok-nc">ApacheLogEvent</span><span class="tok-o">(</span><span class="tok-n">linearray</span><span class="tok-o">(</span><span class="tok-mi">0</span><span class="tok-o">),</span> <span class="tok-n">linearray</span><span class="tok-o">(</span><span class="tok-mi">2</span><span class="tok-o">),</span> <span class="tok-n">timestamp</span><span class="tok-o">,</span> <span class="tok-n">linearray</span><span class="tok-o">(</span><span class="tok-mi">5</span><span class="tok-o">),</span> <span class="tok-n">linearray</span><span class="tok-o">(</span><span class="tok-mi">6</span><span class="tok-o">))</span>
      <span class="tok-o">})</span>
      <span class="tok-o">.</span><span class="tok-n">assignTimestampsAndWatermarks</span><span class="tok-o">(</span>
        <span class="tok-k">new</span> <span class="tok-nc">BoundedOutOfOrdernessTimestampExtractor</span><span class="tok-o">[</span><span class="tok-kt">ApacheLogEvent</span><span class="tok-o">](</span><span class="tok-nc">Time</span><span class="tok-o">.</span><span class="tok-n">milliseconds</span><span class="tok-o">(</span><span class="tok-mi">1000</span><span class="tok-o">))</span> <span class="tok-o">{</span>
          <span class="tok-k">override</span> <span class="tok-k">def</span> <span class="tok-n">extractTimestamp</span><span class="tok-o">(</span><span class="tok-n">t</span><span class="tok-k">:</span> <span class="tok-kt">ApacheLogEvent</span><span class="tok-o">)</span><span class="tok-k">:</span> <span class="tok-kt">Long</span> <span class="tok-o">=</span> <span class="tok-o">{</span>
            <span class="tok-n">t</span><span class="tok-o">.</span><span class="tok-n">eventTime</span>
          <span class="tok-o">}</span>
        <span class="tok-o">}</span>
      <span class="tok-o">)</span>
      <span class="tok-o">.</span><span class="tok-n">keyBy</span><span class="tok-o">(</span><span class="tok-k">_</span><span class="tok-o">.</span><span class="tok-n">url</span><span class="tok-o">)</span>
      <span class="tok-o">.</span><span class="tok-n">timeWindow</span><span class="tok-o">(</span><span class="tok-nc">Time</span><span class="tok-o">.</span><span class="tok-n">minutes</span><span class="tok-o">(</span><span class="tok-mi">10</span><span class="tok-o">),</span> <span class="tok-nc">Time</span><span class="tok-o">.</span><span class="tok-n">seconds</span><span class="tok-o">(</span><span class="tok-mi">5</span><span class="tok-o">))</span>
      <span class="tok-o">.</span><span class="tok-n">aggregate</span><span class="tok-o">(</span><span class="tok-k">new</span> <span class="tok-nc">CountAgg</span><span class="tok-o">(),</span> <span class="tok-k">new</span> <span class="tok-nc">WindowResultFunction</span><span class="tok-o">())</span>
      <span class="tok-o">.</span><span class="tok-n">keyBy</span><span class="tok-o">(</span><span class="tok-k">_</span><span class="tok-o">.</span><span class="tok-n">windowEnd</span><span class="tok-o">)</span>
      <span class="tok-o">.</span><span class="tok-n">process</span><span class="tok-o">(</span><span class="tok-k">new</span> <span class="tok-nc">TopNHotUrls</span><span class="tok-o">(</span><span class="tok-mi">5</span><span class="tok-o">))</span>
      <span class="tok-o">.</span><span class="tok-n">print</span><span class="tok-o">()</span>

    <span class="tok-n">env</span><span class="tok-o">.</span><span class="tok-n">execute</span><span class="tok-o">(</span><span class="tok-s">&quot;Traffic Analysis Job&quot;</span><span class="tok-o">)</span>
  <span class="tok-o">}</span>

  <span class="tok-k">class</span> <span class="tok-nc">CountAgg</span> <span class="tok-k">extends</span> <span class="tok-nc">AggregateFunction</span><span class="tok-o">[</span><span class="tok-kt">ApacheLogEvent</span>, <span class="tok-kt">Long</span>, <span class="tok-kt">Long</span><span class="tok-o">]</span> <span class="tok-o">{</span>
    <span class="tok-k">override</span> <span class="tok-k">def</span> <span class="tok-n">createAccumulator</span><span class="tok-o">()</span><span class="tok-k">:</span> <span class="tok-kt">Long</span> <span class="tok-o">=</span> <span class="tok-mi">0L</span>
    <span class="tok-k">override</span> <span class="tok-k">def</span> <span class="tok-n">add</span><span class="tok-o">(</span><span class="tok-n">apacheLogEvent</span><span class="tok-k">:</span> <span class="tok-kt">ApacheLogEvent</span><span class="tok-o">,</span> <span class="tok-n">acc</span><span class="tok-k">:</span> <span class="tok-kt">Long</span><span class="tok-o">)</span><span class="tok-k">:</span> <span class="tok-kt">Long</span> <span class="tok-o">=</span> <span class="tok-n">acc</span> <span class="tok-o">+</span> <span class="tok-mi">1</span>
    <span class="tok-k">override</span> <span class="tok-k">def</span> <span class="tok-n">getResult</span><span class="tok-o">(</span><span class="tok-n">acc</span><span class="tok-k">:</span> <span class="tok-kt">Long</span><span class="tok-o">)</span><span class="tok-k">:</span> <span class="tok-kt">Long</span> <span class="tok-o">=</span> <span class="tok-n">acc</span>
    <span class="tok-k">override</span> <span class="tok-k">def</span> <span class="tok-n">merge</span><span class="tok-o">(</span><span class="tok-n">acc1</span><span class="tok-k">:</span> <span class="tok-kt">Long</span><span class="tok-o">,</span> <span class="tok-n">acc2</span><span class="tok-k">:</span> <span class="tok-kt">Long</span><span class="tok-o">)</span><span class="tok-k">:</span> <span class="tok-kt">Long</span> <span class="tok-o">=</span> <span class="tok-n">acc1</span> <span class="tok-o">+</span> <span class="tok-n">acc2</span>
  <span class="tok-o">}</span>

  <span class="tok-k">class</span> <span class="tok-nc">WindowResultFunction</span> <span class="tok-k">extends</span> <span class="tok-nc">ProcessWindowFunction</span><span class="tok-o">[</span><span class="tok-kt">Long</span>, <span class="tok-kt">UrlViewCount</span>, <span class="tok-kt">String</span>, <span class="tok-kt">TimeWindow</span><span class="tok-o">]</span> <span class="tok-o">{</span>
    <span class="tok-k">override</span> <span class="tok-k">def</span> <span class="tok-n">process</span><span class="tok-o">(</span><span class="tok-n">key</span><span class="tok-k">:</span> <span class="tok-kt">String</span><span class="tok-o">,</span> <span class="tok-n">context</span><span class="tok-k">:</span> <span class="tok-kt">Context</span><span class="tok-o">,</span> <span class="tok-n">elements</span><span class="tok-k">:</span> <span class="tok-kt">Iterable</span><span class="tok-o">[</span><span class="tok-kt">Long</span><span class="tok-o">],</span> <span class="tok-n">out</span><span class="tok-k">:</span> <span class="tok-kt">Collector</span><span class="tok-o">[</span><span class="tok-kt">UrlViewCount</span><span class="tok-o">])</span><span class="tok-k">:</span> <span class="tok-kt">Unit</span> <span class="tok-o">=</span> <span class="tok-o">{</span>
      <span class="tok-n">out</span><span class="tok-o">.</span><span class="tok-n">collect</span><span class="tok-o">(</span><span class="tok-nc">UrlViewCount</span><span class="tok-o">(</span><span class="tok-n">key</span><span class="tok-o">,</span> <span class="tok-n">context</span><span class="tok-o">.</span><span class="tok-n">window</span><span class="tok-o">.</span><span class="tok-n">getEnd</span><span class="tok-o">,</span> <span class="tok-n">elements</span><span class="tok-o">.</span><span class="tok-n">iterator</span><span class="tok-o">.</span><span class="tok-n">next</span><span class="tok-o">()))</span>
    <span class="tok-o">}</span>
  <span class="tok-o">}</span>

  <span class="tok-k">class</span> <span class="tok-nc">TopNHotUrls</span><span class="tok-o">(</span><span class="tok-n">topSize</span><span class="tok-k">:</span> <span class="tok-kt">Int</span><span class="tok-o">)</span> <span class="tok-k">extends</span> <span class="tok-nc">KeyedProcessFunction</span><span class="tok-o">[</span><span class="tok-kt">Long</span>, <span class="tok-kt">UrlViewCount</span>, <span class="tok-kt">String</span><span class="tok-o">]</span> <span class="tok-o">{</span>

    <span class="tok-k">lazy</span> <span class="tok-k">val</span> <span class="tok-n">urlState</span> <span class="tok-k">=</span> <span class="tok-n">getRuntimeContext</span><span class="tok-o">.</span><span class="tok-n">getListState</span><span class="tok-o">(</span>
      <span class="tok-k">new</span> <span class="tok-nc">ListStateDescriptor</span><span class="tok-o">[</span><span class="tok-kt">UrlViewCount</span><span class="tok-o">](</span><span class="tok-s">&quot;urlState-state&quot;</span><span class="tok-o">,</span> <span class="tok-nc">Types</span><span class="tok-o">.</span><span class="tok-n">of</span><span class="tok-o">[</span><span class="tok-kt">UrlViewCount</span><span class="tok-o">])</span>
    <span class="tok-o">)</span>

    <span class="tok-k">override</span> <span class="tok-k">def</span> <span class="tok-n">processElement</span><span class="tok-o">(</span><span class="tok-n">input</span><span class="tok-k">:</span> <span class="tok-kt">UrlViewCount</span><span class="tok-o">,</span> <span class="tok-n">context</span><span class="tok-k">:</span> <span class="tok-kt">KeyedProcessFunction</span><span class="tok-o">[</span><span class="tok-kt">Long</span>, <span class="tok-kt">UrlViewCount</span>, <span class="tok-kt">String</span><span class="tok-o">]</span><span class="tok-k">#</span><span class="tok-nc">Context</span><span class="tok-o">,</span> <span class="tok-n">collector</span><span class="tok-k">:</span> <span class="tok-kt">Collector</span><span class="tok-o">[</span><span class="tok-kt">String</span><span class="tok-o">])</span><span class="tok-k">:</span> <span class="tok-kt">Unit</span> <span class="tok-o">=</span> <span class="tok-o">{</span>
      <span class="tok-c1">// 每条数据都保存到状态中</span>
      <span class="tok-n">urlState</span><span class="tok-o">.</span><span class="tok-n">add</span><span class="tok-o">(</span><span class="tok-n">input</span><span class="tok-o">)</span>
      <span class="tok-n">context</span><span class="tok-o">.</span><span class="tok-n">timerService</span><span class="tok-o">.</span><span class="tok-n">registerEventTimeTimer</span><span class="tok-o">(</span><span class="tok-n">input</span><span class="tok-o">.</span><span class="tok-n">windowEnd</span> <span class="tok-o">+</span> <span class="tok-mi">1</span><span class="tok-o">)</span>
    <span class="tok-o">}</span>

    <span class="tok-k">override</span> <span class="tok-k">def</span> <span class="tok-n">onTimer</span><span class="tok-o">(</span><span class="tok-n">timestamp</span><span class="tok-k">:</span> <span class="tok-kt">Long</span><span class="tok-o">,</span> <span class="tok-n">ctx</span><span class="tok-k">:</span> <span class="tok-kt">KeyedProcessFunction</span><span class="tok-o">[</span><span class="tok-kt">Long</span>, <span class="tok-kt">UrlViewCount</span>, <span class="tok-kt">String</span><span class="tok-o">]</span><span class="tok-k">#</span><span class="tok-nc">OnTimerContext</span><span class="tok-o">,</span> <span class="tok-n">out</span><span class="tok-k">:</span> <span class="tok-kt">Collector</span><span class="tok-o">[</span><span class="tok-kt">String</span><span class="tok-o">])</span><span class="tok-k">:</span> <span class="tok-kt">Unit</span> <span class="tok-o">=</span> <span class="tok-o">{</span>
      <span class="tok-c1">// 获取收到的所有URL访问量</span>
      <span class="tok-k">val</span> <span class="tok-n">allUrlViews</span><span class="tok-k">:</span> <span class="tok-kt">ListBuffer</span><span class="tok-o">[</span><span class="tok-kt">UrlViewCount</span><span class="tok-o">]</span> <span class="tok-k">=</span> <span class="tok-nc">ListBuffer</span><span class="tok-o">()</span>
      <span class="tok-k">import</span> <span class="tok-nn">scala.collection.JavaConversions._</span>
      <span class="tok-k">for</span> <span class="tok-o">(</span><span class="tok-n">urlView</span> <span class="tok-k">&lt;-</span> <span class="tok-n">urlState</span><span class="tok-o">.</span><span class="tok-n">get</span><span class="tok-o">)</span> <span class="tok-o">{</span>
        <span class="tok-n">allUrlViews</span> <span class="tok-o">+=</span> <span class="tok-n">urlView</span>
      <span class="tok-o">}</span>
      <span class="tok-c1">// 提前清除状态中的数据，释放空间</span>
      <span class="tok-n">urlState</span><span class="tok-o">.</span><span class="tok-n">clear</span><span class="tok-o">()</span>
      <span class="tok-c1">// 按照访问量从大到小排序</span>
      <span class="tok-k">val</span> <span class="tok-n">sortedUrlViews</span> <span class="tok-k">=</span> <span class="tok-n">allUrlViews</span><span class="tok-o">.</span><span class="tok-n">sortBy</span><span class="tok-o">(</span><span class="tok-k">_</span><span class="tok-o">.</span><span class="tok-n">count</span><span class="tok-o">)(</span><span class="tok-nc">Ordering</span><span class="tok-o">.</span><span class="tok-nc">Long</span><span class="tok-o">.</span><span class="tok-n">reverse</span><span class="tok-o">)</span>
        <span class="tok-o">.</span><span class="tok-n">take</span><span class="tok-o">(</span><span class="tok-n">topSize</span><span class="tok-o">)</span>
      <span class="tok-c1">// 将排名信息格式化成 String, 便于打印</span>
      <span class="tok-k">var</span> <span class="tok-n">result</span><span class="tok-k">:</span> <span class="tok-kt">StringBuilder</span> <span class="tok-o">=</span> <span class="tok-k">new</span> <span class="tok-nc">StringBuilder</span>
      <span class="tok-n">result</span>
        <span class="tok-o">.</span><span class="tok-n">append</span><span class="tok-o">(</span><span class="tok-s">&quot;====================================\n&quot;</span><span class="tok-o">)</span>
        <span class="tok-o">.</span><span class="tok-n">append</span><span class="tok-o">(</span><span class="tok-s">&quot;时间: &quot;</span><span class="tok-o">)</span>
        <span class="tok-o">.</span><span class="tok-n">append</span><span class="tok-o">(</span><span class="tok-k">new</span> <span class="tok-nc">Timestamp</span><span class="tok-o">(</span><span class="tok-n">timestamp</span> <span class="tok-o">-</span> <span class="tok-mi">1</span><span class="tok-o">))</span>
        <span class="tok-o">.</span><span class="tok-n">append</span><span class="tok-o">(</span><span class="tok-s">&quot;\n&quot;</span><span class="tok-o">)</span>

      <span class="tok-k">for</span> <span class="tok-o">(</span><span class="tok-n">i</span> <span class="tok-k">&lt;-</span> <span class="tok-n">sortedUrlViews</span><span class="tok-o">.</span><span class="tok-n">indices</span><span class="tok-o">)</span> <span class="tok-o">{</span>
        <span class="tok-k">val</span> <span class="tok-n">currentUrlView</span><span class="tok-k">:</span> <span class="tok-kt">UrlViewCount</span> <span class="tok-o">=</span> <span class="tok-n">sortedUrlViews</span><span class="tok-o">(</span><span class="tok-n">i</span><span class="tok-o">)</span>
        <span class="tok-c1">// e.g.  No1：  URL=/blog/tags/firefox?flav=rss20  流量=55</span>
        <span class="tok-n">result</span>
          <span class="tok-o">.</span><span class="tok-n">append</span><span class="tok-o">(</span><span class="tok-s">&quot;No&quot;</span><span class="tok-o">)</span>
          <span class="tok-o">.</span><span class="tok-n">append</span><span class="tok-o">(</span><span class="tok-n">i</span> <span class="tok-o">+</span> <span class="tok-mi">1</span><span class="tok-o">)</span>
          <span class="tok-o">.</span><span class="tok-n">append</span><span class="tok-o">(</span><span class="tok-s">&quot;: &quot;</span><span class="tok-o">)</span>
          <span class="tok-o">.</span><span class="tok-n">append</span><span class="tok-o">(</span><span class="tok-s">&quot;  URL=&quot;</span><span class="tok-o">)</span>
          <span class="tok-o">.</span><span class="tok-n">append</span><span class="tok-o">(</span><span class="tok-n">currentUrlView</span><span class="tok-o">.</span><span class="tok-n">url</span><span class="tok-o">)</span>
          <span class="tok-o">.</span><span class="tok-n">append</span><span class="tok-o">(</span><span class="tok-s">&quot;  流量=&quot;</span><span class="tok-o">)</span>
          <span class="tok-o">.</span><span class="tok-n">append</span><span class="tok-o">(</span><span class="tok-n">currentUrlView</span><span class="tok-o">.</span><span class="tok-n">count</span><span class="tok-o">)</span>
          <span class="tok-o">.</span><span class="tok-n">append</span><span class="tok-o">(</span><span class="tok-s">&quot;\n&quot;</span><span class="tok-o">)</span>
      <span class="tok-o">}</span>
      <span class="tok-n">result</span>
        <span class="tok-o">.</span><span class="tok-n">append</span><span class="tok-o">(</span><span class="tok-s">&quot;====================================\n\n&quot;</span><span class="tok-o">)</span>
      <span class="tok-c1">// 控制输出频率，模拟实时滚动结果</span>
      <span class="tok-nc">Thread</span><span class="tok-o">.</span><span class="tok-n">sleep</span><span class="tok-o">(</span><span class="tok-mi">1000</span><span class="tok-o">)</span>
      <span class="tok-n">out</span><span class="tok-o">.</span><span class="tok-n">collect</span><span class="tok-o">(</span><span class="tok-n">result</span><span class="tok-o">.</span><span class="tok-n">toString</span><span class="tok-o">)</span>
    <span class="tok-o">}</span>
  <span class="tok-o">}</span>
<span class="tok-o">}</span></code></pre>
</div>
</div>
</div>
<div class="sect2">
<h3 id="_uv统计的布隆过滤器实现">12.4. Uv统计的布隆过滤器实现</h3>
<div class="paragraph">
<p>完整代码如下：</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="pygments highlight"><code data-lang="scala"><span></span><span class="tok-k">package</span> <span class="tok-nn">com.atguigu</span>

<span class="tok-k">import</span> <span class="tok-nn">com.atguigu.UserBehavior.UserAction</span>
<span class="tok-k">import</span> <span class="tok-nn">org.apache.flink.streaming.api.TimeCharacteristic</span>
<span class="tok-k">import</span> <span class="tok-nn">org.apache.flink.streaming.api.scala._</span>
<span class="tok-k">import</span> <span class="tok-nn">org.apache.flink.streaming.api.scala.function.ProcessWindowFunction</span>
<span class="tok-k">import</span> <span class="tok-nn">org.apache.flink.streaming.api.windowing.time.Time</span>
<span class="tok-k">import</span> <span class="tok-nn">org.apache.flink.streaming.api.windowing.triggers.</span><span class="tok-o">{</span><span class="tok-nc">Trigger</span><span class="tok-o">,</span> <span class="tok-nc">TriggerResult</span><span class="tok-o">}</span>
<span class="tok-k">import</span> <span class="tok-nn">org.apache.flink.streaming.api.windowing.triggers.Trigger.TriggerContext</span>
<span class="tok-k">import</span> <span class="tok-nn">org.apache.flink.streaming.api.windowing.windows.TimeWindow</span>
<span class="tok-k">import</span> <span class="tok-nn">org.apache.flink.util.Collector</span>
<span class="tok-k">import</span> <span class="tok-nn">redis.clients.jedis.Jedis</span>

<span class="tok-k">object</span> <span class="tok-nc">UvWithBloomFilter</span> <span class="tok-o">{</span>
  <span class="tok-k">def</span> <span class="tok-n">main</span><span class="tok-o">(</span><span class="tok-n">args</span><span class="tok-k">:</span> <span class="tok-kt">Array</span><span class="tok-o">[</span><span class="tok-kt">String</span><span class="tok-o">])</span><span class="tok-k">:</span> <span class="tok-kt">Unit</span> <span class="tok-o">=</span> <span class="tok-o">{</span>
    <span class="tok-k">val</span> <span class="tok-n">env</span> <span class="tok-k">=</span> <span class="tok-nc">StreamExecutionEnvironment</span><span class="tok-o">.</span><span class="tok-n">getExecutionEnvironment</span>
    <span class="tok-n">env</span><span class="tok-o">.</span><span class="tok-n">setParallelism</span><span class="tok-o">(</span><span class="tok-mi">1</span><span class="tok-o">)</span>
    <span class="tok-n">env</span><span class="tok-o">.</span><span class="tok-n">setStreamTimeCharacteristic</span><span class="tok-o">(</span><span class="tok-nc">TimeCharacteristic</span><span class="tok-o">.</span><span class="tok-nc">EventTime</span><span class="tok-o">)</span>
    <span class="tok-k">val</span> <span class="tok-n">stream</span> <span class="tok-k">=</span> <span class="tok-n">env</span>
      <span class="tok-o">.</span><span class="tok-n">readTextFile</span><span class="tok-o">(</span><span class="tok-s">&quot;/Users/yuanzuo/Desktop/Flink0715Tutorial/src/main/resources/UserBehavior.csv&quot;</span><span class="tok-o">)</span>
      <span class="tok-o">.</span><span class="tok-n">map</span><span class="tok-o">(</span><span class="tok-n">line</span> <span class="tok-k">=&gt;</span> <span class="tok-o">{</span>
        <span class="tok-k">val</span> <span class="tok-n">arr</span> <span class="tok-k">=</span> <span class="tok-n">line</span><span class="tok-o">.</span><span class="tok-n">split</span><span class="tok-o">(</span><span class="tok-s">&quot;,&quot;</span><span class="tok-o">)</span>
        <span class="tok-nc">UserAction</span><span class="tok-o">(</span><span class="tok-n">arr</span><span class="tok-o">(</span><span class="tok-mi">0</span><span class="tok-o">),</span> <span class="tok-n">arr</span><span class="tok-o">(</span><span class="tok-mi">1</span><span class="tok-o">),</span> <span class="tok-n">arr</span><span class="tok-o">(</span><span class="tok-mi">2</span><span class="tok-o">),</span> <span class="tok-n">arr</span><span class="tok-o">(</span><span class="tok-mi">3</span><span class="tok-o">),</span> <span class="tok-n">arr</span><span class="tok-o">(</span><span class="tok-mi">4</span><span class="tok-o">).</span><span class="tok-n">toLong</span> <span class="tok-o">*</span> <span class="tok-mi">1000</span><span class="tok-o">)</span>
      <span class="tok-o">})</span>
      <span class="tok-o">.</span><span class="tok-n">assignAscendingTimestamps</span><span class="tok-o">(</span><span class="tok-k">_</span><span class="tok-o">.</span><span class="tok-n">ts</span><span class="tok-o">)</span>
      <span class="tok-o">.</span><span class="tok-n">filter</span><span class="tok-o">(</span><span class="tok-k">_</span><span class="tok-o">.</span><span class="tok-n">behavior</span> <span class="tok-o">==</span> <span class="tok-s">&quot;pv&quot;</span><span class="tok-o">)</span>
      <span class="tok-o">.</span><span class="tok-n">map</span><span class="tok-o">(</span><span class="tok-n">r</span> <span class="tok-k">=&gt;</span> <span class="tok-o">(</span><span class="tok-s">&quot;dummyKey&quot;</span><span class="tok-o">,</span> <span class="tok-n">r</span><span class="tok-o">.</span><span class="tok-n">userId</span><span class="tok-o">))</span>
      <span class="tok-o">.</span><span class="tok-n">keyBy</span><span class="tok-o">(</span><span class="tok-k">_</span><span class="tok-o">.</span><span class="tok-n">_1</span><span class="tok-o">)</span>
      <span class="tok-o">.</span><span class="tok-n">timeWindow</span><span class="tok-o">(</span><span class="tok-nc">Time</span><span class="tok-o">.</span><span class="tok-n">minutes</span><span class="tok-o">(</span><span class="tok-mi">60</span><span class="tok-o">),</span> <span class="tok-nc">Time</span><span class="tok-o">.</span><span class="tok-n">minutes</span><span class="tok-o">(</span><span class="tok-mi">5</span><span class="tok-o">))</span>
      <span class="tok-o">.</span><span class="tok-n">trigger</span><span class="tok-o">(</span><span class="tok-k">new</span> <span class="tok-nc">MyTrigger123</span><span class="tok-o">)</span>
      <span class="tok-o">.</span><span class="tok-n">process</span><span class="tok-o">(</span><span class="tok-k">new</span> <span class="tok-nc">MyProcess</span><span class="tok-o">)</span>

    <span class="tok-n">stream</span><span class="tok-o">.</span><span class="tok-n">print</span><span class="tok-o">()</span>
    <span class="tok-n">env</span><span class="tok-o">.</span><span class="tok-n">execute</span><span class="tok-o">()</span>
  <span class="tok-o">}</span>

  <span class="tok-k">class</span> <span class="tok-nc">MyProcess</span> <span class="tok-k">extends</span> <span class="tok-nc">ProcessWindowFunction</span><span class="tok-o">[(</span><span class="tok-kt">String</span>, <span class="tok-kt">String</span><span class="tok-o">)</span>, <span class="tok-o">(</span><span class="tok-kt">Long</span>, <span class="tok-kt">Long</span><span class="tok-o">)</span>, <span class="tok-kt">String</span>, <span class="tok-kt">TimeWindow</span><span class="tok-o">]</span> <span class="tok-o">{</span>
    <span class="tok-k">lazy</span> <span class="tok-k">val</span> <span class="tok-n">jedis</span> <span class="tok-k">=</span> <span class="tok-k">new</span> <span class="tok-nc">Jedis</span><span class="tok-o">(</span><span class="tok-s">&quot;localhost&quot;</span><span class="tok-o">,</span> <span class="tok-mi">6379</span><span class="tok-o">)</span>
    <span class="tok-k">lazy</span> <span class="tok-k">val</span> <span class="tok-n">bloom</span> <span class="tok-k">=</span> <span class="tok-k">new</span> <span class="tok-nc">Bloom</span><span class="tok-o">(</span><span class="tok-mi">1</span> <span class="tok-o">&lt;&lt;</span> <span class="tok-mi">29</span><span class="tok-o">)</span>

    <span class="tok-k">override</span> <span class="tok-k">def</span> <span class="tok-n">process</span><span class="tok-o">(</span><span class="tok-n">key</span><span class="tok-k">:</span> <span class="tok-kt">String</span><span class="tok-o">,</span>
                         <span class="tok-n">context</span><span class="tok-k">:</span> <span class="tok-kt">Context</span><span class="tok-o">,</span>
                         <span class="tok-n">vals</span><span class="tok-k">:</span> <span class="tok-kt">Iterable</span><span class="tok-o">[(</span><span class="tok-kt">String</span>, <span class="tok-kt">String</span><span class="tok-o">)],</span>
                         <span class="tok-n">out</span><span class="tok-k">:</span> <span class="tok-kt">Collector</span><span class="tok-o">[(</span><span class="tok-kt">Long</span>, <span class="tok-kt">Long</span><span class="tok-o">)])</span><span class="tok-k">:</span> <span class="tok-kt">Unit</span> <span class="tok-o">=</span> <span class="tok-o">{</span>
      <span class="tok-k">val</span> <span class="tok-n">storeKey</span> <span class="tok-k">=</span> <span class="tok-n">context</span><span class="tok-o">.</span><span class="tok-n">window</span><span class="tok-o">.</span><span class="tok-n">getEnd</span><span class="tok-o">.</span><span class="tok-n">toString</span>
      <span class="tok-k">var</span> <span class="tok-n">count</span> <span class="tok-k">=</span> <span class="tok-mi">0L</span>

      <span class="tok-k">if</span> <span class="tok-o">(</span><span class="tok-n">jedis</span><span class="tok-o">.</span><span class="tok-n">hget</span><span class="tok-o">(</span><span class="tok-s">&quot;UvCountHashTable&quot;</span><span class="tok-o">,</span> <span class="tok-n">storeKey</span><span class="tok-o">)</span> <span class="tok-o">!=</span> <span class="tok-kc">null</span><span class="tok-o">)</span> <span class="tok-o">{</span>
        <span class="tok-n">count</span> <span class="tok-k">=</span> <span class="tok-n">jedis</span><span class="tok-o">.</span><span class="tok-n">hget</span><span class="tok-o">(</span><span class="tok-s">&quot;UvCountHashTable&quot;</span><span class="tok-o">,</span> <span class="tok-n">storeKey</span><span class="tok-o">).</span><span class="tok-n">toLong</span>
      <span class="tok-o">}</span>

      <span class="tok-k">val</span> <span class="tok-n">userId</span> <span class="tok-k">=</span> <span class="tok-n">vals</span><span class="tok-o">.</span><span class="tok-n">last</span><span class="tok-o">.</span><span class="tok-n">_2</span>
      <span class="tok-k">val</span> <span class="tok-n">offset</span> <span class="tok-k">=</span> <span class="tok-n">bloom</span><span class="tok-o">.</span><span class="tok-n">hash</span><span class="tok-o">(</span><span class="tok-n">userId</span><span class="tok-o">,</span> <span class="tok-mi">61</span><span class="tok-o">)</span>

      <span class="tok-k">val</span> <span class="tok-n">isExist</span> <span class="tok-k">=</span> <span class="tok-n">jedis</span><span class="tok-o">.</span><span class="tok-n">getbit</span><span class="tok-o">(</span><span class="tok-n">storeKey</span><span class="tok-o">,</span> <span class="tok-n">offset</span><span class="tok-o">)</span>
      <span class="tok-k">if</span> <span class="tok-o">(!</span><span class="tok-n">isExist</span><span class="tok-o">)</span> <span class="tok-o">{</span>
        <span class="tok-n">jedis</span><span class="tok-o">.</span><span class="tok-n">setbit</span><span class="tok-o">(</span><span class="tok-n">storeKey</span><span class="tok-o">,</span> <span class="tok-n">offset</span><span class="tok-o">,</span> <span class="tok-kc">true</span><span class="tok-o">)</span>
        <span class="tok-n">jedis</span><span class="tok-o">.</span><span class="tok-n">hset</span><span class="tok-o">(</span><span class="tok-s">&quot;UvCountHashTable&quot;</span><span class="tok-o">,</span> <span class="tok-n">storeKey</span><span class="tok-o">,</span> <span class="tok-o">(</span><span class="tok-n">count</span> <span class="tok-o">+</span> <span class="tok-mi">1</span><span class="tok-o">).</span><span class="tok-n">toString</span><span class="tok-o">)</span>
      <span class="tok-o">}</span>



<span class="tok-c1">//      out.collect((count, storeKey.toLong))</span>

    <span class="tok-o">}</span>
  <span class="tok-o">}</span>

  <span class="tok-k">class</span> <span class="tok-nc">MyTrigger123</span> <span class="tok-k">extends</span> <span class="tok-nc">Trigger</span><span class="tok-o">[(</span><span class="tok-kt">String</span>, <span class="tok-kt">String</span><span class="tok-o">)</span>, <span class="tok-kt">TimeWindow</span><span class="tok-o">]</span> <span class="tok-o">{</span>
    <span class="tok-k">override</span> <span class="tok-k">def</span> <span class="tok-n">onEventTime</span><span class="tok-o">(</span><span class="tok-n">time</span><span class="tok-k">:</span> <span class="tok-kt">Long</span><span class="tok-o">,</span>
                             <span class="tok-n">window</span><span class="tok-k">:</span> <span class="tok-kt">TimeWindow</span><span class="tok-o">,</span>
                             <span class="tok-n">ctx</span><span class="tok-k">:</span> <span class="tok-kt">TriggerContext</span><span class="tok-o">)</span><span class="tok-k">:</span> <span class="tok-kt">TriggerResult</span> <span class="tok-o">=</span> <span class="tok-o">{</span>
      <span class="tok-k">if</span> <span class="tok-o">(</span><span class="tok-n">ctx</span><span class="tok-o">.</span><span class="tok-n">getCurrentWatermark</span> <span class="tok-o">&gt;=</span> <span class="tok-n">window</span><span class="tok-o">.</span><span class="tok-n">getEnd</span><span class="tok-o">)</span> <span class="tok-o">{</span>
        <span class="tok-k">val</span> <span class="tok-n">jedis</span> <span class="tok-k">=</span> <span class="tok-k">new</span> <span class="tok-nc">Jedis</span><span class="tok-o">(</span><span class="tok-s">&quot;localhost&quot;</span><span class="tok-o">,</span> <span class="tok-mi">6379</span><span class="tok-o">)</span>
        <span class="tok-k">val</span> <span class="tok-n">key</span> <span class="tok-k">=</span> <span class="tok-n">window</span><span class="tok-o">.</span><span class="tok-n">getEnd</span><span class="tok-o">.</span><span class="tok-n">toString</span>
        <span class="tok-nc">TriggerResult</span><span class="tok-o">.</span><span class="tok-nc">FIRE_AND_PURGE</span>
        <span class="tok-n">println</span><span class="tok-o">(</span><span class="tok-n">key</span><span class="tok-o">,</span> <span class="tok-n">jedis</span><span class="tok-o">.</span><span class="tok-n">hget</span><span class="tok-o">(</span><span class="tok-s">&quot;UvCountHashTable&quot;</span><span class="tok-o">,</span> <span class="tok-n">key</span><span class="tok-o">))</span>
      <span class="tok-o">}</span>
      <span class="tok-nc">TriggerResult</span><span class="tok-o">.</span><span class="tok-nc">CONTINUE</span>
    <span class="tok-o">}</span>
    <span class="tok-k">override</span> <span class="tok-k">def</span> <span class="tok-n">onProcessingTime</span><span class="tok-o">(</span><span class="tok-n">time</span><span class="tok-k">:</span> <span class="tok-kt">Long</span><span class="tok-o">,</span>
                                  <span class="tok-n">window</span><span class="tok-k">:</span> <span class="tok-kt">TimeWindow</span><span class="tok-o">,</span>
                                  <span class="tok-n">ctx</span><span class="tok-k">:</span> <span class="tok-kt">TriggerContext</span><span class="tok-o">)</span><span class="tok-k">:</span> <span class="tok-kt">TriggerResult</span> <span class="tok-o">=</span> <span class="tok-o">{</span>
      <span class="tok-nc">TriggerResult</span><span class="tok-o">.</span><span class="tok-nc">CONTINUE</span>
    <span class="tok-o">}</span>
    <span class="tok-k">override</span> <span class="tok-k">def</span> <span class="tok-n">clear</span><span class="tok-o">(</span><span class="tok-n">window</span><span class="tok-k">:</span> <span class="tok-kt">TimeWindow</span><span class="tok-o">,</span> <span class="tok-n">ctx</span><span class="tok-k">:</span> <span class="tok-kt">Trigger.TriggerContext</span><span class="tok-o">)</span><span class="tok-k">:</span> <span class="tok-kt">Unit</span> <span class="tok-o">=</span> <span class="tok-o">{}</span>
    <span class="tok-k">override</span> <span class="tok-k">def</span> <span class="tok-n">onElement</span><span class="tok-o">(</span><span class="tok-n">element</span><span class="tok-k">:</span> <span class="tok-o">(</span><span class="tok-kt">String</span><span class="tok-o">,</span> <span class="tok-kt">String</span><span class="tok-o">),</span>
                           <span class="tok-n">timestamp</span><span class="tok-k">:</span> <span class="tok-kt">Long</span><span class="tok-o">,</span>
                           <span class="tok-n">window</span><span class="tok-k">:</span> <span class="tok-kt">TimeWindow</span><span class="tok-o">,</span>
                           <span class="tok-n">ctx</span><span class="tok-k">:</span> <span class="tok-kt">TriggerContext</span><span class="tok-o">)</span><span class="tok-k">:</span> <span class="tok-kt">TriggerResult</span> <span class="tok-o">=</span> <span class="tok-o">{</span>
      <span class="tok-nc">TriggerResult</span><span class="tok-o">.</span><span class="tok-nc">FIRE_AND_PURGE</span>
    <span class="tok-o">}</span>
  <span class="tok-o">}</span>

  <span class="tok-k">class</span> <span class="tok-nc">Bloom</span><span class="tok-o">(</span><span class="tok-n">size</span><span class="tok-k">:</span> <span class="tok-kt">Long</span><span class="tok-o">)</span> <span class="tok-k">extends</span> <span class="tok-nc">Serializable</span> <span class="tok-o">{</span>
    <span class="tok-k">private</span> <span class="tok-k">val</span> <span class="tok-n">cap</span> <span class="tok-k">=</span> <span class="tok-n">size</span>

    <span class="tok-k">def</span> <span class="tok-n">hash</span><span class="tok-o">(</span><span class="tok-n">value</span><span class="tok-k">:</span> <span class="tok-kt">String</span><span class="tok-o">,</span> <span class="tok-n">seed</span><span class="tok-k">:</span> <span class="tok-kt">Int</span><span class="tok-o">)</span><span class="tok-k">:</span> <span class="tok-kt">Long</span> <span class="tok-o">=</span> <span class="tok-o">{</span>
      <span class="tok-k">var</span> <span class="tok-n">result</span> <span class="tok-k">=</span> <span class="tok-mi">0</span>
      <span class="tok-k">for</span> <span class="tok-o">(</span><span class="tok-n">i</span> <span class="tok-k">&lt;-</span> <span class="tok-mi">0</span> <span class="tok-n">until</span> <span class="tok-n">value</span><span class="tok-o">.</span><span class="tok-n">length</span><span class="tok-o">)</span> <span class="tok-o">{</span>
        <span class="tok-n">result</span> <span class="tok-k">=</span> <span class="tok-n">result</span> <span class="tok-o">*</span> <span class="tok-n">seed</span> <span class="tok-o">+</span> <span class="tok-n">value</span><span class="tok-o">.</span><span class="tok-n">charAt</span><span class="tok-o">(</span><span class="tok-n">i</span><span class="tok-o">)</span>
      <span class="tok-o">}</span>
      <span class="tok-o">(</span><span class="tok-n">cap</span> <span class="tok-o">-</span> <span class="tok-mi">1</span><span class="tok-o">)</span> <span class="tok-o">&amp;</span> <span class="tok-n">result</span>
    <span class="tok-o">}</span>
  <span class="tok-o">}</span>
<span class="tok-o">}</span></code></pre>
</div>
</div>
</div>
<div class="sect2">
<h3 id="_app分渠道数据统计">12.5. APP分渠道数据统计</h3>
<div class="paragraph">
<p>完整代码如下：</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="pygments highlight"><code data-lang="scala"><span></span><span class="tok-k">package</span> <span class="tok-nn">com.atguigu</span>

<span class="tok-k">import</span> <span class="tok-nn">java.util.</span><span class="tok-o">{</span><span class="tok-nc">Calendar</span><span class="tok-o">,</span> <span class="tok-nc">UUID</span><span class="tok-o">}</span>

<span class="tok-k">import</span> <span class="tok-nn">org.apache.flink.streaming.api.TimeCharacteristic</span>
<span class="tok-k">import</span> <span class="tok-nn">org.apache.flink.streaming.api.functions.source.RichParallelSourceFunction</span>
<span class="tok-k">import</span> <span class="tok-nn">org.apache.flink.streaming.api.functions.source.SourceFunction.SourceContext</span>
<span class="tok-k">import</span> <span class="tok-nn">org.apache.flink.streaming.api.scala._</span>
<span class="tok-k">import</span> <span class="tok-nn">org.apache.flink.streaming.api.scala.function.ProcessWindowFunction</span>
<span class="tok-k">import</span> <span class="tok-nn">org.apache.flink.streaming.api.windowing.time.Time</span>
<span class="tok-k">import</span> <span class="tok-nn">org.apache.flink.streaming.api.windowing.windows.TimeWindow</span>
<span class="tok-k">import</span> <span class="tok-nn">org.apache.flink.util.Collector</span>

<span class="tok-k">import</span> <span class="tok-nn">scala.util.Random</span>

<span class="tok-k">object</span> <span class="tok-nc">AppMarketingByChannel</span> <span class="tok-o">{</span>
  <span class="tok-k">case</span> <span class="tok-k">class</span> <span class="tok-nc">MarketingUserBehavior</span><span class="tok-o">(</span><span class="tok-n">userId</span><span class="tok-k">:</span> <span class="tok-kt">String</span><span class="tok-o">,</span>
                                   <span class="tok-n">behavior</span><span class="tok-k">:</span> <span class="tok-kt">String</span><span class="tok-o">,</span>
                                   <span class="tok-n">channel</span><span class="tok-k">:</span> <span class="tok-kt">String</span><span class="tok-o">,</span>
                                   <span class="tok-n">ts</span><span class="tok-k">:</span> <span class="tok-kt">Long</span><span class="tok-o">)</span>

  <span class="tok-k">class</span> <span class="tok-nc">SimulatedEventSource</span> <span class="tok-k">extends</span> <span class="tok-nc">RichParallelSourceFunction</span><span class="tok-o">[</span><span class="tok-kt">MarketingUserBehavior</span><span class="tok-o">]</span> <span class="tok-o">{</span>
    <span class="tok-k">var</span> <span class="tok-n">running</span> <span class="tok-k">=</span> <span class="tok-kc">true</span>

    <span class="tok-k">val</span> <span class="tok-n">channelSet</span> <span class="tok-k">=</span> <span class="tok-nc">Seq</span><span class="tok-o">(</span><span class="tok-s">&quot;AppStore&quot;</span><span class="tok-o">,</span> <span class="tok-s">&quot;XiaomiStore&quot;</span><span class="tok-o">)</span>
    <span class="tok-k">val</span> <span class="tok-n">behaviorTypes</span> <span class="tok-k">=</span> <span class="tok-nc">Seq</span><span class="tok-o">(</span><span class="tok-s">&quot;BROWSE&quot;</span><span class="tok-o">,</span> <span class="tok-s">&quot;CLICK&quot;</span><span class="tok-o">)</span>
    <span class="tok-k">val</span> <span class="tok-n">rand</span> <span class="tok-k">=</span> <span class="tok-k">new</span> <span class="tok-nc">Random</span>

    <span class="tok-k">override</span> <span class="tok-k">def</span> <span class="tok-n">run</span><span class="tok-o">(</span><span class="tok-n">ctx</span><span class="tok-k">:</span> <span class="tok-kt">SourceContext</span><span class="tok-o">[</span><span class="tok-kt">MarketingUserBehavior</span><span class="tok-o">])</span><span class="tok-k">:</span> <span class="tok-kt">Unit</span> <span class="tok-o">=</span> <span class="tok-o">{</span>
      <span class="tok-k">while</span> <span class="tok-o">(</span><span class="tok-n">running</span><span class="tok-o">)</span> <span class="tok-o">{</span>
        <span class="tok-k">val</span> <span class="tok-n">userId</span> <span class="tok-k">=</span> <span class="tok-nc">UUID</span><span class="tok-o">.</span><span class="tok-n">randomUUID</span><span class="tok-o">().</span><span class="tok-n">toString</span>
        <span class="tok-k">val</span> <span class="tok-n">behaviorType</span> <span class="tok-k">=</span> <span class="tok-n">behaviorTypes</span><span class="tok-o">(</span><span class="tok-n">rand</span><span class="tok-o">.</span><span class="tok-n">nextInt</span><span class="tok-o">(</span><span class="tok-n">behaviorTypes</span><span class="tok-o">.</span><span class="tok-n">size</span><span class="tok-o">))</span>
        <span class="tok-k">val</span> <span class="tok-n">channel</span> <span class="tok-k">=</span> <span class="tok-n">channelSet</span><span class="tok-o">(</span><span class="tok-n">rand</span><span class="tok-o">.</span><span class="tok-n">nextInt</span><span class="tok-o">(</span><span class="tok-n">channelSet</span><span class="tok-o">.</span><span class="tok-n">size</span><span class="tok-o">))</span>
        <span class="tok-k">val</span> <span class="tok-n">ts</span> <span class="tok-k">=</span> <span class="tok-nc">Calendar</span><span class="tok-o">.</span><span class="tok-n">getInstance</span><span class="tok-o">().</span><span class="tok-n">getTimeInMillis</span>

        <span class="tok-n">ctx</span><span class="tok-o">.</span><span class="tok-n">collect</span><span class="tok-o">(</span><span class="tok-nc">MarketingUserBehavior</span><span class="tok-o">(</span><span class="tok-n">userId</span><span class="tok-o">,</span> <span class="tok-n">behaviorType</span><span class="tok-o">,</span> <span class="tok-n">channel</span><span class="tok-o">,</span> <span class="tok-n">ts</span><span class="tok-o">))</span>

        <span class="tok-nc">Thread</span><span class="tok-o">.</span><span class="tok-n">sleep</span><span class="tok-o">(</span><span class="tok-mi">10</span><span class="tok-o">)</span>
      <span class="tok-o">}</span>
    <span class="tok-o">}</span>

    <span class="tok-k">override</span> <span class="tok-k">def</span> <span class="tok-n">cancel</span><span class="tok-o">()</span><span class="tok-k">:</span> <span class="tok-kt">Unit</span> <span class="tok-o">=</span> <span class="tok-n">running</span> <span class="tok-k">=</span> <span class="tok-kc">false</span>
  <span class="tok-o">}</span>

  <span class="tok-k">def</span> <span class="tok-n">main</span><span class="tok-o">(</span><span class="tok-n">args</span><span class="tok-k">:</span> <span class="tok-kt">Array</span><span class="tok-o">[</span><span class="tok-kt">String</span><span class="tok-o">])</span><span class="tok-k">:</span> <span class="tok-kt">Unit</span> <span class="tok-o">=</span> <span class="tok-o">{</span>
    <span class="tok-k">val</span> <span class="tok-n">env</span> <span class="tok-k">=</span> <span class="tok-nc">StreamExecutionEnvironment</span><span class="tok-o">.</span><span class="tok-n">getExecutionEnvironment</span>
    <span class="tok-n">env</span><span class="tok-o">.</span><span class="tok-n">setParallelism</span><span class="tok-o">(</span><span class="tok-mi">1</span><span class="tok-o">)</span>
    <span class="tok-n">env</span><span class="tok-o">.</span><span class="tok-n">setStreamTimeCharacteristic</span><span class="tok-o">(</span><span class="tok-nc">TimeCharacteristic</span><span class="tok-o">.</span><span class="tok-nc">EventTime</span><span class="tok-o">)</span>
    <span class="tok-k">val</span> <span class="tok-n">stream</span> <span class="tok-k">=</span> <span class="tok-n">env</span>
      <span class="tok-o">.</span><span class="tok-n">addSource</span><span class="tok-o">(</span><span class="tok-k">new</span> <span class="tok-nc">SimulatedEventSource</span><span class="tok-o">)</span>
      <span class="tok-o">.</span><span class="tok-n">assignAscendingTimestamps</span><span class="tok-o">(</span><span class="tok-k">_</span><span class="tok-o">.</span><span class="tok-n">ts</span><span class="tok-o">)</span>
      <span class="tok-o">.</span><span class="tok-n">filter</span><span class="tok-o">(</span><span class="tok-k">_</span><span class="tok-o">.</span><span class="tok-n">behavior</span> <span class="tok-o">!=</span> <span class="tok-s">&quot;UNINSTALL&quot;</span><span class="tok-o">)</span>
      <span class="tok-o">.</span><span class="tok-n">map</span><span class="tok-o">(</span><span class="tok-n">r</span> <span class="tok-k">=&gt;</span> <span class="tok-o">{</span>
        <span class="tok-o">((</span><span class="tok-n">r</span><span class="tok-o">.</span><span class="tok-n">channel</span><span class="tok-o">,</span> <span class="tok-n">r</span><span class="tok-o">.</span><span class="tok-n">behavior</span><span class="tok-o">),</span> <span class="tok-mi">1L</span><span class="tok-o">)</span>
      <span class="tok-o">})</span>
      <span class="tok-o">.</span><span class="tok-n">keyBy</span><span class="tok-o">(</span><span class="tok-k">_</span><span class="tok-o">.</span><span class="tok-n">_1</span><span class="tok-o">)</span>
      <span class="tok-o">.</span><span class="tok-n">timeWindow</span><span class="tok-o">(</span><span class="tok-nc">Time</span><span class="tok-o">.</span><span class="tok-n">seconds</span><span class="tok-o">(</span><span class="tok-mi">5</span><span class="tok-o">),</span> <span class="tok-nc">Time</span><span class="tok-o">.</span><span class="tok-n">seconds</span><span class="tok-o">(</span><span class="tok-mi">1</span><span class="tok-o">))</span>
      <span class="tok-o">.</span><span class="tok-n">process</span><span class="tok-o">(</span><span class="tok-k">new</span> <span class="tok-nc">MarketingCountByChannel</span><span class="tok-o">)</span>
    <span class="tok-n">stream</span><span class="tok-o">.</span><span class="tok-n">print</span><span class="tok-o">()</span>
    <span class="tok-n">env</span><span class="tok-o">.</span><span class="tok-n">execute</span><span class="tok-o">()</span>
  <span class="tok-o">}</span>

  <span class="tok-k">class</span> <span class="tok-nc">MarketingCountByChannel</span> <span class="tok-k">extends</span> <span class="tok-nc">ProcessWindowFunction</span><span class="tok-o">[((</span><span class="tok-kt">String</span>, <span class="tok-kt">String</span><span class="tok-o">)</span>, <span class="tok-kt">Long</span><span class="tok-o">)</span>,<span class="tok-o">(</span><span class="tok-kt">String</span>, <span class="tok-kt">Long</span>, <span class="tok-kt">Long</span><span class="tok-o">)</span>, <span class="tok-o">(</span><span class="tok-kt">String</span>, <span class="tok-kt">String</span><span class="tok-o">)</span>, <span class="tok-kt">TimeWindow</span><span class="tok-o">]</span> <span class="tok-o">{</span>
    <span class="tok-k">override</span> <span class="tok-k">def</span> <span class="tok-n">process</span><span class="tok-o">(</span><span class="tok-n">key</span><span class="tok-k">:</span>  <span class="tok-o">(</span><span class="tok-kt">String</span><span class="tok-o">,</span><span class="tok-kt">String</span><span class="tok-o">),</span>
                         <span class="tok-n">context</span><span class="tok-k">:</span> <span class="tok-kt">Context</span><span class="tok-o">,</span>
                         <span class="tok-n">elements</span><span class="tok-k">:</span> <span class="tok-kt">Iterable</span><span class="tok-o">[((</span><span class="tok-kt">String</span>, <span class="tok-kt">String</span><span class="tok-o">)</span>, <span class="tok-kt">Long</span><span class="tok-o">)],</span>
                         <span class="tok-n">out</span><span class="tok-k">:</span> <span class="tok-kt">Collector</span><span class="tok-o">[(</span><span class="tok-kt">String</span>, <span class="tok-kt">Long</span>, <span class="tok-kt">Long</span><span class="tok-o">)])</span><span class="tok-k">:</span> <span class="tok-kt">Unit</span> <span class="tok-o">=</span> <span class="tok-o">{</span>
<span class="tok-c1">//      val t = (&quot;a&quot;,)</span>

      <span class="tok-n">out</span><span class="tok-o">.</span><span class="tok-n">collect</span><span class="tok-o">((</span><span class="tok-n">key</span><span class="tok-o">.</span><span class="tok-n">_1</span><span class="tok-o">,</span> <span class="tok-n">elements</span><span class="tok-o">.</span><span class="tok-n">size</span><span class="tok-o">,</span> <span class="tok-n">context</span><span class="tok-o">.</span><span class="tok-n">window</span><span class="tok-o">.</span><span class="tok-n">getEnd</span><span class="tok-o">))</span>

    <span class="tok-o">}</span>
  <span class="tok-o">}</span>
<span class="tok-o">}</span></code></pre>
</div>
</div>
</div>
<div class="sect2">
<h3 id="_app不分渠道数据统计">12.6. APP不分渠道数据统计</h3>
<div class="paragraph">
<p>完整代码如下：</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="pygments highlight"><code data-lang="scala"><span></span><span class="tok-k">package</span> <span class="tok-nn">com.atguigu</span>

<span class="tok-k">import</span> <span class="tok-nn">com.atguigu.AppMarketingByChannel.SimulatedEventSource</span>
<span class="tok-k">import</span> <span class="tok-nn">org.apache.flink.streaming.api.TimeCharacteristic</span>
<span class="tok-k">import</span> <span class="tok-nn">org.apache.flink.streaming.api.scala._</span>
<span class="tok-k">import</span> <span class="tok-nn">org.apache.flink.streaming.api.scala.function.ProcessWindowFunction</span>
<span class="tok-k">import</span> <span class="tok-nn">org.apache.flink.streaming.api.windowing.time.Time</span>
<span class="tok-k">import</span> <span class="tok-nn">org.apache.flink.streaming.api.windowing.windows.TimeWindow</span>
<span class="tok-k">import</span> <span class="tok-nn">org.apache.flink.util.Collector</span>

<span class="tok-k">object</span> <span class="tok-nc">AppMarketingStatistics</span> <span class="tok-o">{</span>
  <span class="tok-k">def</span> <span class="tok-n">main</span><span class="tok-o">(</span><span class="tok-n">args</span><span class="tok-k">:</span> <span class="tok-kt">Array</span><span class="tok-o">[</span><span class="tok-kt">String</span><span class="tok-o">])</span><span class="tok-k">:</span> <span class="tok-kt">Unit</span> <span class="tok-o">=</span> <span class="tok-o">{</span>
    <span class="tok-k">val</span> <span class="tok-n">env</span> <span class="tok-k">=</span> <span class="tok-nc">StreamExecutionEnvironment</span><span class="tok-o">.</span><span class="tok-n">getExecutionEnvironment</span>
    <span class="tok-n">env</span><span class="tok-o">.</span><span class="tok-n">setParallelism</span><span class="tok-o">(</span><span class="tok-mi">1</span><span class="tok-o">)</span>
    <span class="tok-n">env</span><span class="tok-o">.</span><span class="tok-n">setStreamTimeCharacteristic</span><span class="tok-o">(</span><span class="tok-nc">TimeCharacteristic</span><span class="tok-o">.</span><span class="tok-nc">EventTime</span><span class="tok-o">)</span>
    <span class="tok-k">val</span> <span class="tok-n">stream</span> <span class="tok-k">=</span> <span class="tok-n">env</span>
      <span class="tok-o">.</span><span class="tok-n">addSource</span><span class="tok-o">(</span><span class="tok-k">new</span> <span class="tok-nc">SimulatedEventSource</span><span class="tok-o">)</span>
      <span class="tok-o">.</span><span class="tok-n">assignAscendingTimestamps</span><span class="tok-o">(</span><span class="tok-k">_</span><span class="tok-o">.</span><span class="tok-n">ts</span><span class="tok-o">)</span>
      <span class="tok-o">.</span><span class="tok-n">filter</span><span class="tok-o">(</span><span class="tok-k">_</span><span class="tok-o">.</span><span class="tok-n">behavior</span> <span class="tok-o">!=</span> <span class="tok-s">&quot;UNINSTALL&quot;</span><span class="tok-o">)</span>
      <span class="tok-o">.</span><span class="tok-n">map</span><span class="tok-o">(</span><span class="tok-n">r</span> <span class="tok-k">=&gt;</span> <span class="tok-o">{</span>
        <span class="tok-o">(</span><span class="tok-s">&quot;dummyKey&quot;</span><span class="tok-o">,</span> <span class="tok-mi">1L</span><span class="tok-o">)</span>
      <span class="tok-o">})</span>
      <span class="tok-o">.</span><span class="tok-n">keyBy</span><span class="tok-o">(</span><span class="tok-k">_</span><span class="tok-o">.</span><span class="tok-n">_1</span><span class="tok-o">)</span>
      <span class="tok-o">.</span><span class="tok-n">timeWindow</span><span class="tok-o">(</span><span class="tok-nc">Time</span><span class="tok-o">.</span><span class="tok-n">seconds</span><span class="tok-o">(</span><span class="tok-mi">5</span><span class="tok-o">),</span> <span class="tok-nc">Time</span><span class="tok-o">.</span><span class="tok-n">seconds</span><span class="tok-o">(</span><span class="tok-mi">1</span><span class="tok-o">))</span>
      <span class="tok-o">.</span><span class="tok-n">process</span><span class="tok-o">(</span><span class="tok-k">new</span> <span class="tok-nc">MarketingCountTotal</span><span class="tok-o">)</span>
    <span class="tok-n">stream</span><span class="tok-o">.</span><span class="tok-n">print</span><span class="tok-o">()</span>
    <span class="tok-n">env</span><span class="tok-o">.</span><span class="tok-n">execute</span><span class="tok-o">()</span>
  <span class="tok-o">}</span>

  <span class="tok-k">class</span> <span class="tok-nc">MarketingCountTotal</span> <span class="tok-k">extends</span> <span class="tok-nc">ProcessWindowFunction</span><span class="tok-o">[(</span><span class="tok-kt">String</span>, <span class="tok-kt">Long</span><span class="tok-o">)</span>,
  <span class="tok-o">(</span><span class="tok-kt">String</span>, <span class="tok-kt">Long</span>, <span class="tok-kt">Long</span><span class="tok-o">)</span>, <span class="tok-kt">String</span>, <span class="tok-kt">TimeWindow</span><span class="tok-o">]</span> <span class="tok-o">{</span>
    <span class="tok-k">override</span> <span class="tok-k">def</span> <span class="tok-n">process</span><span class="tok-o">(</span><span class="tok-n">key</span><span class="tok-k">:</span> <span class="tok-kt">String</span><span class="tok-o">,</span>
                         <span class="tok-n">context</span><span class="tok-k">:</span> <span class="tok-kt">Context</span><span class="tok-o">,</span>
                         <span class="tok-n">elements</span><span class="tok-k">:</span> <span class="tok-kt">Iterable</span><span class="tok-o">[(</span><span class="tok-kt">String</span>, <span class="tok-kt">Long</span><span class="tok-o">)],</span>
                         <span class="tok-n">out</span><span class="tok-k">:</span> <span class="tok-kt">Collector</span><span class="tok-o">[(</span><span class="tok-kt">String</span>, <span class="tok-kt">Long</span>, <span class="tok-kt">Long</span><span class="tok-o">)])</span><span class="tok-k">:</span> <span class="tok-kt">Unit</span> <span class="tok-o">=</span> <span class="tok-o">{</span>
      <span class="tok-n">out</span><span class="tok-o">.</span><span class="tok-n">collect</span><span class="tok-o">((</span><span class="tok-n">key</span><span class="tok-o">,</span> <span class="tok-n">elements</span><span class="tok-o">.</span><span class="tok-n">size</span><span class="tok-o">,</span> <span class="tok-n">context</span><span class="tok-o">.</span><span class="tok-n">window</span><span class="tok-o">.</span><span class="tok-n">getEnd</span><span class="tok-o">))</span>
    <span class="tok-o">}</span>
  <span class="tok-o">}</span>
<span class="tok-o">}</span></code></pre>
</div>
</div>
</div>
<div class="sect2">
<h3 id="_恶意登陆实现">12.7. 恶意登陆实现</h3>
<div class="listingblock">
<div class="content">
<pre class="pygments highlight"><code data-lang="scala"><span></span><span class="tok-k">package</span> <span class="tok-nn">com.atguigu</span>

<span class="tok-k">import</span> <span class="tok-nn">com.atguigu.FlinkCepExample.LoginEvent</span>
<span class="tok-k">import</span> <span class="tok-nn">org.apache.flink.api.common.state.</span><span class="tok-o">{</span><span class="tok-nc">ListStateDescriptor</span><span class="tok-o">,</span> <span class="tok-nc">ValueStateDescriptor</span><span class="tok-o">}</span>
<span class="tok-k">import</span> <span class="tok-nn">org.apache.flink.api.scala.typeutils.Types</span>
<span class="tok-k">import</span> <span class="tok-nn">org.apache.flink.cep.scala.pattern.Pattern</span>
<span class="tok-k">import</span> <span class="tok-nn">org.apache.flink.streaming.api.TimeCharacteristic</span>
<span class="tok-k">import</span> <span class="tok-nn">org.apache.flink.streaming.api.functions.KeyedProcessFunction</span>
<span class="tok-k">import</span> <span class="tok-nn">org.apache.flink.streaming.api.scala._</span>
<span class="tok-k">import</span> <span class="tok-nn">org.apache.flink.util.Collector</span>

<span class="tok-k">import</span> <span class="tok-nn">scala.collection.mutable.ListBuffer</span>

<span class="tok-k">object</span> <span class="tok-nc">LoginFailWithoutCEP</span> <span class="tok-o">{</span>
  <span class="tok-k">def</span> <span class="tok-n">main</span><span class="tok-o">(</span><span class="tok-n">args</span><span class="tok-k">:</span> <span class="tok-kt">Array</span><span class="tok-o">[</span><span class="tok-kt">String</span><span class="tok-o">])</span><span class="tok-k">:</span> <span class="tok-kt">Unit</span> <span class="tok-o">=</span> <span class="tok-o">{</span>
    <span class="tok-k">val</span> <span class="tok-n">env</span> <span class="tok-k">=</span> <span class="tok-nc">StreamExecutionEnvironment</span><span class="tok-o">.</span><span class="tok-n">getExecutionEnvironment</span>
    <span class="tok-n">env</span><span class="tok-o">.</span><span class="tok-n">setStreamTimeCharacteristic</span><span class="tok-o">(</span><span class="tok-nc">TimeCharacteristic</span><span class="tok-o">.</span><span class="tok-nc">EventTime</span><span class="tok-o">)</span>
    <span class="tok-n">env</span><span class="tok-o">.</span><span class="tok-n">setParallelism</span><span class="tok-o">(</span><span class="tok-mi">1</span><span class="tok-o">)</span>

    <span class="tok-k">val</span> <span class="tok-n">stream</span> <span class="tok-k">=</span> <span class="tok-n">env</span>
      <span class="tok-o">.</span><span class="tok-n">fromElements</span><span class="tok-o">(</span>
        <span class="tok-nc">LoginEvent</span><span class="tok-o">(</span><span class="tok-s">&quot;1&quot;</span><span class="tok-o">,</span> <span class="tok-s">&quot;0.0.0.0&quot;</span><span class="tok-o">,</span> <span class="tok-s">&quot;fail&quot;</span><span class="tok-o">,</span> <span class="tok-s">&quot;1&quot;</span><span class="tok-o">),</span>
        <span class="tok-nc">LoginEvent</span><span class="tok-o">(</span><span class="tok-s">&quot;1&quot;</span><span class="tok-o">,</span> <span class="tok-s">&quot;0.0.0.0&quot;</span><span class="tok-o">,</span> <span class="tok-s">&quot;success&quot;</span><span class="tok-o">,</span> <span class="tok-s">&quot;2&quot;</span><span class="tok-o">),</span>
        <span class="tok-nc">LoginEvent</span><span class="tok-o">(</span><span class="tok-s">&quot;1&quot;</span><span class="tok-o">,</span> <span class="tok-s">&quot;0.0.0.0&quot;</span><span class="tok-o">,</span> <span class="tok-s">&quot;fail&quot;</span><span class="tok-o">,</span> <span class="tok-s">&quot;3&quot;</span><span class="tok-o">),</span>
        <span class="tok-nc">LoginEvent</span><span class="tok-o">(</span><span class="tok-s">&quot;1&quot;</span><span class="tok-o">,</span> <span class="tok-s">&quot;0.0.0.0&quot;</span><span class="tok-o">,</span> <span class="tok-s">&quot;fail&quot;</span><span class="tok-o">,</span> <span class="tok-s">&quot;4&quot;</span><span class="tok-o">)</span>
      <span class="tok-o">)</span>
      <span class="tok-o">.</span><span class="tok-n">assignAscendingTimestamps</span><span class="tok-o">(</span><span class="tok-k">_</span><span class="tok-o">.</span><span class="tok-n">ts</span><span class="tok-o">.</span><span class="tok-n">toLong</span> <span class="tok-o">*</span> <span class="tok-mi">1000</span><span class="tok-o">)</span>
      <span class="tok-o">.</span><span class="tok-n">keyBy</span><span class="tok-o">(</span><span class="tok-k">_</span><span class="tok-o">.</span><span class="tok-n">userId</span><span class="tok-o">)</span>
      <span class="tok-o">.</span><span class="tok-n">process</span><span class="tok-o">(</span><span class="tok-k">new</span> <span class="tok-nc">MatchFunction</span><span class="tok-o">)</span>

    <span class="tok-n">stream</span><span class="tok-o">.</span><span class="tok-n">print</span><span class="tok-o">()</span>
    <span class="tok-n">env</span><span class="tok-o">.</span><span class="tok-n">execute</span><span class="tok-o">()</span>
  <span class="tok-o">}</span>

  <span class="tok-k">class</span> <span class="tok-nc">MatchFunction</span> <span class="tok-k">extends</span> <span class="tok-nc">KeyedProcessFunction</span><span class="tok-o">[</span><span class="tok-kt">String</span>, <span class="tok-kt">LoginEvent</span>, <span class="tok-kt">String</span><span class="tok-o">]</span> <span class="tok-o">{</span>

    <span class="tok-k">lazy</span> <span class="tok-k">val</span> <span class="tok-n">loginState</span> <span class="tok-k">=</span> <span class="tok-n">getRuntimeContext</span><span class="tok-o">.</span><span class="tok-n">getListState</span><span class="tok-o">(</span>
      <span class="tok-k">new</span> <span class="tok-nc">ListStateDescriptor</span><span class="tok-o">[</span><span class="tok-kt">LoginEvent</span><span class="tok-o">](</span><span class="tok-s">&quot;login-fail&quot;</span><span class="tok-o">,</span> <span class="tok-nc">Types</span><span class="tok-o">.</span><span class="tok-n">of</span><span class="tok-o">[</span><span class="tok-kt">LoginEvent</span><span class="tok-o">])</span>
    <span class="tok-o">)</span>

    <span class="tok-k">lazy</span> <span class="tok-k">val</span> <span class="tok-n">timestamp</span> <span class="tok-k">=</span> <span class="tok-n">getRuntimeContext</span><span class="tok-o">.</span><span class="tok-n">getState</span><span class="tok-o">(</span>
      <span class="tok-k">new</span> <span class="tok-nc">ValueStateDescriptor</span><span class="tok-o">[</span><span class="tok-kt">Long</span><span class="tok-o">](</span><span class="tok-s">&quot;ts&quot;</span><span class="tok-o">,</span> <span class="tok-nc">Types</span><span class="tok-o">.</span><span class="tok-n">of</span><span class="tok-o">[</span><span class="tok-kt">Long</span><span class="tok-o">])</span>
    <span class="tok-o">)</span>

    <span class="tok-k">override</span> <span class="tok-k">def</span> <span class="tok-n">processElement</span><span class="tok-o">(</span><span class="tok-n">value</span><span class="tok-k">:</span> <span class="tok-kt">LoginEvent</span><span class="tok-o">,</span>
                                <span class="tok-n">ctx</span><span class="tok-k">:</span> <span class="tok-kt">KeyedProcessFunction</span><span class="tok-o">[</span><span class="tok-kt">String</span>, <span class="tok-kt">LoginEvent</span>, <span class="tok-kt">String</span><span class="tok-o">]</span><span class="tok-k">#</span><span class="tok-nc">Context</span><span class="tok-o">,</span>
                                <span class="tok-n">out</span><span class="tok-k">:</span> <span class="tok-kt">Collector</span><span class="tok-o">[</span><span class="tok-kt">String</span><span class="tok-o">])</span><span class="tok-k">:</span> <span class="tok-kt">Unit</span> <span class="tok-o">=</span> <span class="tok-o">{</span>
      <span class="tok-k">if</span> <span class="tok-o">(</span><span class="tok-n">value</span><span class="tok-o">.</span><span class="tok-n">loginStatus</span> <span class="tok-o">==</span> <span class="tok-s">&quot;fail&quot;</span><span class="tok-o">)</span> <span class="tok-o">{</span>
        <span class="tok-n">loginState</span><span class="tok-o">.</span><span class="tok-n">add</span><span class="tok-o">(</span><span class="tok-n">value</span><span class="tok-o">)</span>
        <span class="tok-k">if</span> <span class="tok-o">(!</span><span class="tok-n">timestamp</span><span class="tok-o">.</span><span class="tok-n">value</span><span class="tok-o">())</span> <span class="tok-o">{</span>
          <span class="tok-n">timestamp</span><span class="tok-o">.</span><span class="tok-n">update</span><span class="tok-o">(</span><span class="tok-n">value</span><span class="tok-o">.</span><span class="tok-n">ts</span><span class="tok-o">.</span><span class="tok-n">toLong</span> <span class="tok-o">*</span> <span class="tok-mi">1000</span> <span class="tok-o">+</span> <span class="tok-mi">5000L</span><span class="tok-o">)</span>
          <span class="tok-n">ctx</span><span class="tok-o">.</span><span class="tok-n">timerService</span><span class="tok-o">().</span><span class="tok-n">registerEventTimeTimer</span><span class="tok-o">(</span><span class="tok-n">value</span><span class="tok-o">.</span><span class="tok-n">ts</span><span class="tok-o">.</span><span class="tok-n">toLong</span> <span class="tok-o">*</span> <span class="tok-mi">1000</span> <span class="tok-o">+</span> <span class="tok-mi">5000L</span><span class="tok-o">)</span>
        <span class="tok-o">}</span>
      <span class="tok-o">}</span>

      <span class="tok-k">if</span> <span class="tok-o">(</span><span class="tok-n">value</span><span class="tok-o">.</span><span class="tok-n">loginStatus</span> <span class="tok-o">==</span> <span class="tok-s">&quot;success&quot;</span><span class="tok-o">)</span> <span class="tok-o">{</span>
        <span class="tok-n">loginState</span><span class="tok-o">.</span><span class="tok-n">clear</span><span class="tok-o">()</span>
        <span class="tok-n">ctx</span><span class="tok-o">.</span><span class="tok-n">timerService</span><span class="tok-o">().</span><span class="tok-n">deleteEventTimeTimer</span><span class="tok-o">(</span><span class="tok-n">timestamp</span><span class="tok-o">.</span><span class="tok-n">value</span><span class="tok-o">())</span>
      <span class="tok-o">}</span>
    <span class="tok-o">}</span>

    <span class="tok-k">override</span> <span class="tok-k">def</span> <span class="tok-n">onTimer</span><span class="tok-o">(</span><span class="tok-n">ts</span><span class="tok-k">:</span> <span class="tok-kt">Long</span><span class="tok-o">,</span>
                         <span class="tok-n">ctx</span><span class="tok-k">:</span> <span class="tok-kt">KeyedProcessFunction</span><span class="tok-o">[</span><span class="tok-kt">String</span>, <span class="tok-kt">LoginEvent</span>, <span class="tok-kt">String</span><span class="tok-o">]</span><span class="tok-k">#</span><span class="tok-nc">OnTimerContext</span><span class="tok-o">,</span>
                         <span class="tok-n">out</span><span class="tok-k">:</span> <span class="tok-kt">Collector</span><span class="tok-o">[</span><span class="tok-kt">String</span><span class="tok-o">])</span><span class="tok-k">:</span> <span class="tok-kt">Unit</span> <span class="tok-o">=</span> <span class="tok-o">{</span>
      <span class="tok-k">val</span> <span class="tok-n">allLogins</span> <span class="tok-k">=</span> <span class="tok-nc">ListBuffer</span><span class="tok-o">[</span><span class="tok-kt">LoginEvent</span><span class="tok-o">]()</span>
      <span class="tok-k">import</span> <span class="tok-nn">scala.collection.JavaConversions._</span>
      <span class="tok-k">for</span> <span class="tok-o">(</span><span class="tok-n">login</span> <span class="tok-k">&lt;-</span> <span class="tok-n">loginState</span><span class="tok-o">.</span><span class="tok-n">get</span><span class="tok-o">)</span> <span class="tok-o">{</span>
        <span class="tok-n">allLogins</span> <span class="tok-o">+=</span> <span class="tok-n">login</span>
      <span class="tok-o">}</span>
      <span class="tok-n">loginState</span><span class="tok-o">.</span><span class="tok-n">clear</span><span class="tok-o">()</span>

      <span class="tok-k">if</span> <span class="tok-o">(</span><span class="tok-n">allLogins</span><span class="tok-o">.</span><span class="tok-n">length</span> <span class="tok-o">&gt;</span> <span class="tok-mi">1</span><span class="tok-o">)</span> <span class="tok-o">{</span>
        <span class="tok-n">out</span><span class="tok-o">.</span><span class="tok-n">collect</span><span class="tok-o">(</span><span class="tok-s">&quot;5s以内连续两次登陆失败&quot;</span><span class="tok-o">)</span>
      <span class="tok-o">}</span>
    <span class="tok-o">}</span>
  <span class="tok-o">}</span>
<span class="tok-o">}</span></code></pre>
</div>
</div>
</div>
<div class="sect2">
<h3 id="_订单支付实时监控">12.8. 订单支付实时监控</h3>
<div class="ulist">
<ul>
<li>
<p>基本需求</p>
<div class="ulist">
<ul>
<li>
<p>用户下单之后，应设置订单失效时间，以提高用户支付的意愿，并降低系统风险</p>
</li>
<li>
<p>用户下单后15分钟未支付，则输出监控信息</p>
</li>
</ul>
</div>
</li>
<li>
<p>解决思路</p>
<div class="ulist">
<ul>
<li>
<p>利用CEP库进行事件流的模式匹配，并设定匹配的时间间隔</p>
</li>
</ul>
</div>
</li>
</ul>
</div>
<div class="sect3">
<h4 id="_使用flink_cep来实现">12.8.1. 使用Flink CEP来实现</h4>
<div class="paragraph">
<p>在电商平台中，最终创造收入和利润的是用户下单购买的环节；更具体一点，是用户真正完成支付动作的时候。用户下单的行为可以表明用户对商品的需求，但在现实中，并不是每次下单都会被用户立刻支付。当拖延一段时间后，用户支付的意愿会降低。所以为了让用户更有紧迫感从而提高支付转化率，同时也为了防范订单支付环节的安全风险，电商网站往往会对订单状态进行监控，设置一个失效时间（比如15分钟），如果下单后一段时间仍未支付，订单就会被取消。</p>
</div>
<div class="paragraph">
<p>我们将会利用CEP库来实现这个功能。我们先将事件流按照订单号orderId分流，然后定义这样的一个事件模式：在15分钟内，事件“create”与“pay”严格紧邻：</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="pygments highlight"><code data-lang="scala"><span></span><span class="tok-k">val</span> <span class="tok-n">orderPayPattern</span> <span class="tok-k">=</span> <span class="tok-nc">Pattern</span><span class="tok-o">.</span><span class="tok-n">begin</span><span class="tok-o">[</span><span class="tok-kt">OrderEvent</span><span class="tok-o">](</span><span class="tok-s">&quot;begin&quot;</span><span class="tok-o">)</span>
  <span class="tok-o">.</span><span class="tok-n">where</span><span class="tok-o">(</span><span class="tok-k">_</span><span class="tok-o">.</span><span class="tok-n">eventType</span> <span class="tok-o">==</span> <span class="tok-s">&quot;create&quot;</span><span class="tok-o">)</span>
  <span class="tok-o">.</span><span class="tok-n">next</span><span class="tok-o">(</span><span class="tok-s">&quot;next&quot;</span><span class="tok-o">)</span>
  <span class="tok-o">.</span><span class="tok-n">where</span><span class="tok-o">(</span><span class="tok-k">_</span><span class="tok-o">.</span><span class="tok-n">eventType</span> <span class="tok-o">==</span> <span class="tok-s">&quot;pay&quot;</span><span class="tok-o">)</span>
  <span class="tok-o">.</span><span class="tok-n">within</span><span class="tok-o">(</span><span class="tok-nc">Time</span><span class="tok-o">.</span><span class="tok-n">seconds</span><span class="tok-o">(</span><span class="tok-mi">5</span><span class="tok-o">))</span></code></pre>
</div>
</div>
<div class="paragraph">
<p>这样调用.select方法时，就可以同时获取到匹配出的事件和超时未匹配的事件了。
在src/main/scala下继续创建OrderTimeout.scala文件，新建一个单例对象。定义样例类OrderEvent，这是输入的订单事件流；另外还有OrderResult，这是输出显示的订单状态结果。由于没有现成的数据，我们还是用几条自定义的示例数据来做演示。
完整代码如下：</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="pygments highlight"><code data-lang="scala"><span></span><span class="tok-k">import</span> <span class="tok-nn">org.apache.flink.cep.scala.CEP</span>
<span class="tok-k">import</span> <span class="tok-nn">org.apache.flink.cep.scala.pattern.Pattern</span>
<span class="tok-k">import</span> <span class="tok-nn">org.apache.flink.streaming.api.scala._</span>
<span class="tok-k">import</span> <span class="tok-nn">org.apache.flink.streaming.api.windowing.time.Time</span>
<span class="tok-k">import</span> <span class="tok-nn">org.apache.flink.streaming.api.TimeCharacteristic</span>
<span class="tok-k">import</span> <span class="tok-nn">org.apache.flink.util.Collector</span>
<span class="tok-k">import</span> <span class="tok-nn">scala.collection.Map</span>

<span class="tok-k">case</span> <span class="tok-k">class</span> <span class="tok-nc">OrderEvent</span><span class="tok-o">(</span><span class="tok-n">orderId</span><span class="tok-k">:</span> <span class="tok-kt">String</span><span class="tok-o">,</span> <span class="tok-n">eventType</span><span class="tok-k">:</span> <span class="tok-kt">String</span><span class="tok-o">,</span> <span class="tok-n">eventTime</span><span class="tok-k">:</span> <span class="tok-kt">String</span><span class="tok-o">)</span>

<span class="tok-k">object</span> <span class="tok-nc">OrderTimeout</span> <span class="tok-o">{</span>

  <span class="tok-k">def</span> <span class="tok-n">main</span><span class="tok-o">(</span><span class="tok-n">args</span><span class="tok-k">:</span> <span class="tok-kt">Array</span><span class="tok-o">[</span><span class="tok-kt">String</span><span class="tok-o">])</span><span class="tok-k">:</span> <span class="tok-kt">Unit</span> <span class="tok-o">=</span> <span class="tok-o">{</span>

    <span class="tok-k">val</span> <span class="tok-n">env</span> <span class="tok-k">=</span> <span class="tok-nc">StreamExecutionEnvironment</span><span class="tok-o">.</span><span class="tok-n">getExecutionEnvironment</span>
    <span class="tok-n">env</span><span class="tok-o">.</span><span class="tok-n">setParallelism</span><span class="tok-o">(</span><span class="tok-mi">1</span><span class="tok-o">)</span>
    <span class="tok-n">env</span><span class="tok-o">.</span><span class="tok-n">setStreamTimeCharacteristic</span><span class="tok-o">(</span><span class="tok-nc">TimeCharacteristic</span><span class="tok-o">.</span><span class="tok-nc">EventTime</span><span class="tok-o">)</span>

    <span class="tok-k">val</span> <span class="tok-n">orderEventStream</span> <span class="tok-k">=</span> <span class="tok-n">env</span><span class="tok-o">.</span><span class="tok-n">fromCollection</span><span class="tok-o">(</span><span class="tok-nc">List</span><span class="tok-o">(</span>
      <span class="tok-nc">OrderEvent</span><span class="tok-o">(</span><span class="tok-s">&quot;1&quot;</span><span class="tok-o">,</span> <span class="tok-s">&quot;create&quot;</span><span class="tok-o">,</span> <span class="tok-s">&quot;1558430842&quot;</span><span class="tok-o">),</span>
      <span class="tok-nc">OrderEvent</span><span class="tok-o">(</span><span class="tok-s">&quot;2&quot;</span><span class="tok-o">,</span> <span class="tok-s">&quot;create&quot;</span><span class="tok-o">,</span> <span class="tok-s">&quot;1558430843&quot;</span><span class="tok-o">),</span>
      <span class="tok-nc">OrderEvent</span><span class="tok-o">(</span><span class="tok-s">&quot;2&quot;</span><span class="tok-o">,</span> <span class="tok-s">&quot;pay&quot;</span><span class="tok-o">,</span> <span class="tok-s">&quot;1558430844&quot;</span><span class="tok-o">),</span>
      <span class="tok-nc">OrderEvent</span><span class="tok-o">(</span><span class="tok-s">&quot;3&quot;</span><span class="tok-o">,</span> <span class="tok-s">&quot;pay&quot;</span><span class="tok-o">,</span> <span class="tok-s">&quot;1558430942&quot;</span><span class="tok-o">),</span>
      <span class="tok-nc">OrderEvent</span><span class="tok-o">(</span><span class="tok-s">&quot;4&quot;</span><span class="tok-o">,</span> <span class="tok-s">&quot;pay&quot;</span><span class="tok-o">,</span> <span class="tok-s">&quot;1558430943&quot;</span><span class="tok-o">)</span>
    <span class="tok-o">)).</span><span class="tok-n">assignAscendingTimestamps</span><span class="tok-o">(</span><span class="tok-k">_</span><span class="tok-o">.</span><span class="tok-n">eventTime</span><span class="tok-o">.</span><span class="tok-n">toLong</span> <span class="tok-o">*</span> <span class="tok-mi">1000</span><span class="tok-o">)</span>

<span class="tok-c1">//    val orders: DataStream[String] = env.socketTextStream(&quot;localhost&quot;, 9999)</span>
<span class="tok-c1">//</span>
<span class="tok-c1">//    val orderEventStream = orders</span>
<span class="tok-c1">//      .map(s =&gt; {</span>
<span class="tok-c1">//        println(s)</span>
<span class="tok-c1">//        val slist = s.split(&quot;\\|&quot;)</span>
<span class="tok-c1">//        println(slist)</span>
<span class="tok-c1">//        OrderEvent(slist(0), slist(1), slist(2))</span>
<span class="tok-c1">//      })</span>
<span class="tok-c1">//      .assignAscendingTimestamps(_.eventTime.toLong * 1000)</span>

    <span class="tok-k">val</span> <span class="tok-n">orderPayPattern</span> <span class="tok-k">=</span> <span class="tok-nc">Pattern</span><span class="tok-o">.</span><span class="tok-n">begin</span><span class="tok-o">[</span><span class="tok-kt">OrderEvent</span><span class="tok-o">](</span><span class="tok-s">&quot;begin&quot;</span><span class="tok-o">)</span>
      <span class="tok-o">.</span><span class="tok-n">where</span><span class="tok-o">(</span><span class="tok-k">_</span><span class="tok-o">.</span><span class="tok-n">eventType</span><span class="tok-o">.</span><span class="tok-n">equals</span><span class="tok-o">(</span><span class="tok-s">&quot;create&quot;</span><span class="tok-o">))</span>
      <span class="tok-o">.</span><span class="tok-n">next</span><span class="tok-o">(</span><span class="tok-s">&quot;next&quot;</span><span class="tok-o">)</span>
      <span class="tok-o">.</span><span class="tok-n">where</span><span class="tok-o">(</span><span class="tok-k">_</span><span class="tok-o">.</span><span class="tok-n">eventType</span><span class="tok-o">.</span><span class="tok-n">equals</span><span class="tok-o">(</span><span class="tok-s">&quot;pay&quot;</span><span class="tok-o">))</span>
      <span class="tok-o">.</span><span class="tok-n">within</span><span class="tok-o">(</span><span class="tok-nc">Time</span><span class="tok-o">.</span><span class="tok-n">seconds</span><span class="tok-o">(</span><span class="tok-mi">5</span><span class="tok-o">))</span>

    <span class="tok-k">val</span> <span class="tok-n">orderTimeoutOutput</span> <span class="tok-k">=</span> <span class="tok-nc">OutputTag</span><span class="tok-o">[</span><span class="tok-kt">OrderEvent</span><span class="tok-o">](</span><span class="tok-s">&quot;orderTimeout&quot;</span><span class="tok-o">)</span>

    <span class="tok-k">val</span> <span class="tok-n">patternStream</span> <span class="tok-k">=</span> <span class="tok-nc">CEP</span><span class="tok-o">.</span><span class="tok-n">pattern</span><span class="tok-o">(</span><span class="tok-n">orderEventStream</span><span class="tok-o">.</span><span class="tok-n">keyBy</span><span class="tok-o">(</span><span class="tok-s">&quot;orderId&quot;</span><span class="tok-o">),</span> <span class="tok-n">orderPayPattern</span><span class="tok-o">)</span>

    <span class="tok-k">val</span> <span class="tok-n">timeoutFunction</span> <span class="tok-k">=</span> <span class="tok-o">(</span><span class="tok-n">map</span><span class="tok-k">:</span> <span class="tok-kt">Map</span><span class="tok-o">[</span><span class="tok-kt">String</span>, <span class="tok-kt">Iterable</span><span class="tok-o">[</span><span class="tok-kt">OrderEvent</span><span class="tok-o">]],</span> <span class="tok-n">timestamp</span><span class="tok-k">:</span> <span class="tok-kt">Long</span><span class="tok-o">,</span> <span class="tok-n">out</span><span class="tok-k">:</span> <span class="tok-kt">Collector</span><span class="tok-o">[</span><span class="tok-kt">OrderEvent</span><span class="tok-o">])</span> <span class="tok-k">=&gt;</span> <span class="tok-o">{</span>
      <span class="tok-n">print</span><span class="tok-o">(</span><span class="tok-n">timestamp</span><span class="tok-o">)</span>
      <span class="tok-k">val</span> <span class="tok-n">orderStart</span> <span class="tok-k">=</span> <span class="tok-n">map</span><span class="tok-o">.</span><span class="tok-n">get</span><span class="tok-o">(</span><span class="tok-s">&quot;begin&quot;</span><span class="tok-o">).</span><span class="tok-n">get</span><span class="tok-o">.</span><span class="tok-n">head</span>
      <span class="tok-n">out</span><span class="tok-o">.</span><span class="tok-n">collect</span><span class="tok-o">(</span><span class="tok-n">orderStart</span><span class="tok-o">)</span>
    <span class="tok-o">}</span>

    <span class="tok-k">val</span> <span class="tok-n">selectFunction</span> <span class="tok-k">=</span> <span class="tok-o">(</span><span class="tok-n">map</span><span class="tok-k">:</span> <span class="tok-kt">Map</span><span class="tok-o">[</span><span class="tok-kt">String</span>, <span class="tok-kt">Iterable</span><span class="tok-o">[</span><span class="tok-kt">OrderEvent</span><span class="tok-o">]],</span> <span class="tok-n">out</span><span class="tok-k">:</span> <span class="tok-kt">Collector</span><span class="tok-o">[</span><span class="tok-kt">OrderEvent</span><span class="tok-o">])</span> <span class="tok-k">=&gt;</span> <span class="tok-o">{</span>
    <span class="tok-o">}</span>

    <span class="tok-k">val</span> <span class="tok-n">timeoutOrder</span> <span class="tok-k">=</span> <span class="tok-n">patternStream</span><span class="tok-o">.</span><span class="tok-n">flatSelect</span><span class="tok-o">(</span><span class="tok-n">orderTimeoutOutput</span><span class="tok-o">)(</span><span class="tok-n">timeoutFunction</span><span class="tok-o">)(</span><span class="tok-n">selectFunction</span><span class="tok-o">)</span>

    <span class="tok-n">timeoutOrder</span><span class="tok-o">.</span><span class="tok-n">getSideOutput</span><span class="tok-o">(</span><span class="tok-n">orderTimeoutOutput</span><span class="tok-o">).</span><span class="tok-n">print</span><span class="tok-o">()</span>

    <span class="tok-n">env</span><span class="tok-o">.</span><span class="tok-n">execute</span>

  <span class="tok-o">}</span>
<span class="tok-o">}</span></code></pre>
</div>
</div>
</div>
<div class="sect3">
<h4 id="_使用process_function实现订单超时需求">12.8.2. 使用Process Function实现订单超时需求</h4>
<div class="listingblock">
<div class="title">OrderTimeoutWithoutCep.scala</div>
<div class="content">
<pre class="pygments highlight"><code data-lang="scala"><span></span><span class="tok-k">import</span> <span class="tok-nn">org.apache.flink.api.common.state.</span><span class="tok-o">{</span><span class="tok-nc">ValueState</span><span class="tok-o">,</span> <span class="tok-nc">ValueStateDescriptor</span><span class="tok-o">}</span>
<span class="tok-k">import</span> <span class="tok-nn">org.apache.flink.streaming.api.TimeCharacteristic</span>
<span class="tok-k">import</span> <span class="tok-nn">org.apache.flink.streaming.api.functions.KeyedProcessFunction</span>
<span class="tok-k">import</span> <span class="tok-nn">org.apache.flink.streaming.api.scala.StreamExecutionEnvironment</span>
<span class="tok-k">import</span> <span class="tok-nn">org.apache.flink.streaming.api.scala._</span>
<span class="tok-k">import</span> <span class="tok-nn">org.apache.flink.util.Collector</span>

<span class="tok-k">case</span> <span class="tok-k">class</span> <span class="tok-nc">OrderEvent1</span><span class="tok-o">(</span><span class="tok-n">orderId</span><span class="tok-k">:</span> <span class="tok-kt">String</span><span class="tok-o">,</span>
                      <span class="tok-n">eventType</span><span class="tok-k">:</span> <span class="tok-kt">String</span><span class="tok-o">,</span>
                      <span class="tok-n">eventTime</span><span class="tok-k">:</span> <span class="tok-kt">String</span><span class="tok-o">)</span>

<span class="tok-k">object</span> <span class="tok-nc">OrderTimeoutWithoutCep</span> <span class="tok-o">{</span>
  <span class="tok-k">def</span> <span class="tok-n">main</span><span class="tok-o">(</span><span class="tok-n">args</span><span class="tok-k">:</span> <span class="tok-kt">Array</span><span class="tok-o">[</span><span class="tok-kt">String</span><span class="tok-o">])</span><span class="tok-k">:</span> <span class="tok-kt">Unit</span> <span class="tok-o">=</span> <span class="tok-o">{</span>
    <span class="tok-k">val</span> <span class="tok-n">env</span> <span class="tok-k">=</span> <span class="tok-nc">StreamExecutionEnvironment</span><span class="tok-o">.</span><span class="tok-n">getExecutionEnvironment</span>
    <span class="tok-n">env</span><span class="tok-o">.</span><span class="tok-n">setParallelism</span><span class="tok-o">(</span><span class="tok-mi">1</span><span class="tok-o">)</span>
    <span class="tok-n">env</span><span class="tok-o">.</span><span class="tok-n">setStreamTimeCharacteristic</span><span class="tok-o">(</span><span class="tok-nc">TimeCharacteristic</span><span class="tok-o">.</span><span class="tok-nc">EventTime</span><span class="tok-o">)</span>

    <span class="tok-k">val</span> <span class="tok-n">orderEventsStream</span> <span class="tok-k">=</span> <span class="tok-n">env</span><span class="tok-o">.</span><span class="tok-n">fromCollection</span><span class="tok-o">(</span><span class="tok-nc">List</span><span class="tok-o">(</span>
      <span class="tok-nc">OrderEvent1</span><span class="tok-o">(</span><span class="tok-s">&quot;1&quot;</span><span class="tok-o">,</span> <span class="tok-s">&quot;create&quot;</span><span class="tok-o">,</span> <span class="tok-s">&quot;1558430842&quot;</span><span class="tok-o">),</span>
      <span class="tok-nc">OrderEvent1</span><span class="tok-o">(</span><span class="tok-s">&quot;2&quot;</span><span class="tok-o">,</span> <span class="tok-s">&quot;create&quot;</span><span class="tok-o">,</span> <span class="tok-s">&quot;1558430843&quot;</span><span class="tok-o">),</span>
      <span class="tok-nc">OrderEvent1</span><span class="tok-o">(</span><span class="tok-s">&quot;2&quot;</span><span class="tok-o">,</span> <span class="tok-s">&quot;pay&quot;</span><span class="tok-o">,</span> <span class="tok-s">&quot;1558430844&quot;</span><span class="tok-o">),</span>
      <span class="tok-nc">OrderEvent1</span><span class="tok-o">(</span><span class="tok-s">&quot;3&quot;</span><span class="tok-o">,</span> <span class="tok-s">&quot;pay&quot;</span><span class="tok-o">,</span> <span class="tok-s">&quot;1558430942&quot;</span><span class="tok-o">),</span>
      <span class="tok-nc">OrderEvent1</span><span class="tok-o">(</span><span class="tok-s">&quot;4&quot;</span><span class="tok-o">,</span> <span class="tok-s">&quot;pay&quot;</span><span class="tok-o">,</span> <span class="tok-s">&quot;1558430943&quot;</span><span class="tok-o">)</span>
    <span class="tok-o">)).</span><span class="tok-n">assignAscendingTimestamps</span><span class="tok-o">(</span><span class="tok-k">_</span><span class="tok-o">.</span><span class="tok-n">eventTime</span><span class="tok-o">.</span><span class="tok-n">toLong</span> <span class="tok-o">*</span> <span class="tok-mi">1000</span><span class="tok-o">)</span>

    <span class="tok-k">val</span> <span class="tok-n">orders</span> <span class="tok-k">=</span> <span class="tok-n">orderEventsStream</span>
      <span class="tok-o">.</span><span class="tok-n">keyBy</span><span class="tok-o">(</span><span class="tok-k">_</span><span class="tok-o">.</span><span class="tok-n">orderId</span><span class="tok-o">)</span>
      <span class="tok-o">.</span><span class="tok-n">process</span><span class="tok-o">(</span><span class="tok-k">new</span> <span class="tok-nc">OrderMatchFunction</span><span class="tok-o">)</span>
      <span class="tok-o">.</span><span class="tok-n">print</span><span class="tok-o">()</span>

    <span class="tok-n">env</span><span class="tok-o">.</span><span class="tok-n">execute</span>
  <span class="tok-o">}</span>

  <span class="tok-k">class</span> <span class="tok-nc">OrderMatchFunction</span> <span class="tok-k">extends</span> <span class="tok-nc">KeyedProcessFunction</span><span class="tok-o">[</span><span class="tok-kt">String</span>,
    <span class="tok-kt">OrderEvent1</span>, <span class="tok-kt">OrderEvent1</span><span class="tok-o">]</span> <span class="tok-o">{</span>
    <span class="tok-k">lazy</span> <span class="tok-k">val</span> <span class="tok-n">orderState</span><span class="tok-k">:</span> <span class="tok-kt">ValueState</span><span class="tok-o">[</span><span class="tok-kt">OrderEvent1</span><span class="tok-o">]</span> <span class="tok-k">=</span> <span class="tok-n">getRuntimeContext</span>
      <span class="tok-o">.</span><span class="tok-n">getState</span><span class="tok-o">(</span><span class="tok-k">new</span> <span class="tok-nc">ValueStateDescriptor</span><span class="tok-o">[</span><span class="tok-kt">OrderEvent1</span><span class="tok-o">](</span><span class="tok-s">&quot;saved order&quot;</span><span class="tok-o">,</span>
        <span class="tok-n">classOf</span><span class="tok-o">[</span><span class="tok-kt">OrderEvent1</span><span class="tok-o">]))</span>

    <span class="tok-k">override</span> <span class="tok-k">def</span> <span class="tok-n">processElement</span><span class="tok-o">(</span><span class="tok-n">order</span><span class="tok-k">:</span> <span class="tok-kt">OrderEvent1</span><span class="tok-o">,</span>
                                <span class="tok-n">context</span><span class="tok-k">:</span> <span class="tok-kt">KeyedProcessFunction</span><span class="tok-o">[</span>
                                  <span class="tok-kt">String</span>, <span class="tok-kt">OrderEvent1</span>, <span class="tok-kt">OrderEvent1</span><span class="tok-o">]</span><span class="tok-k">#</span><span class="tok-nc">Context</span><span class="tok-o">,</span>
                                <span class="tok-n">out</span><span class="tok-k">:</span> <span class="tok-kt">Collector</span><span class="tok-o">[</span><span class="tok-kt">OrderEvent1</span><span class="tok-o">])</span><span class="tok-k">:</span> <span class="tok-kt">Unit</span> <span class="tok-o">=</span> <span class="tok-o">{</span>
      <span class="tok-k">val</span> <span class="tok-n">timerService</span> <span class="tok-k">=</span> <span class="tok-n">context</span><span class="tok-o">.</span><span class="tok-n">timerService</span>

      <span class="tok-k">if</span> <span class="tok-o">(</span><span class="tok-n">order</span><span class="tok-o">.</span><span class="tok-n">eventType</span> <span class="tok-o">==</span> <span class="tok-s">&quot;create&quot;</span><span class="tok-o">)</span> <span class="tok-o">{</span>
        <span class="tok-k">if</span> <span class="tok-o">(</span><span class="tok-n">orderState</span><span class="tok-o">.</span><span class="tok-n">value</span><span class="tok-o">()</span> <span class="tok-o">==</span> <span class="tok-kc">null</span><span class="tok-o">)</span> <span class="tok-o">{</span>
          <span class="tok-n">orderState</span><span class="tok-o">.</span><span class="tok-n">update</span><span class="tok-o">(</span><span class="tok-n">order</span><span class="tok-o">)</span>
        <span class="tok-o">}</span>
      <span class="tok-o">}</span> <span class="tok-k">else</span> <span class="tok-o">{</span>
        <span class="tok-n">orderState</span><span class="tok-o">.</span><span class="tok-n">update</span><span class="tok-o">(</span><span class="tok-n">order</span><span class="tok-o">)</span>
      <span class="tok-o">}</span>

      <span class="tok-n">timerService</span><span class="tok-o">.</span><span class="tok-n">registerEventTimeTimer</span><span class="tok-o">(</span>
        <span class="tok-n">order</span><span class="tok-o">.</span><span class="tok-n">eventTime</span><span class="tok-o">.</span><span class="tok-n">toLong</span> <span class="tok-o">*</span> <span class="tok-mi">1000</span> <span class="tok-o">+</span> <span class="tok-mi">5</span> <span class="tok-o">*</span> <span class="tok-mi">1000</span>
      <span class="tok-o">)</span>
    <span class="tok-o">}</span>

    <span class="tok-k">override</span> <span class="tok-k">def</span> <span class="tok-n">onTimer</span><span class="tok-o">(</span><span class="tok-n">timestamp</span><span class="tok-k">:</span> <span class="tok-kt">Long</span><span class="tok-o">,</span>
                         <span class="tok-n">ctx</span><span class="tok-k">:</span> <span class="tok-kt">KeyedProcessFunction</span><span class="tok-o">[</span>
                           <span class="tok-kt">String</span>, <span class="tok-kt">OrderEvent1</span>, <span class="tok-kt">OrderEvent1</span><span class="tok-o">]</span><span class="tok-k">#</span><span class="tok-nc">OnTimerContext</span><span class="tok-o">,</span>
                         <span class="tok-n">out</span><span class="tok-k">:</span> <span class="tok-kt">Collector</span><span class="tok-o">[</span><span class="tok-kt">OrderEvent1</span><span class="tok-o">])</span><span class="tok-k">:</span> <span class="tok-kt">Unit</span> <span class="tok-o">=</span> <span class="tok-o">{</span>
      <span class="tok-k">val</span> <span class="tok-n">savedOrder</span> <span class="tok-k">=</span> <span class="tok-n">orderState</span><span class="tok-o">.</span><span class="tok-n">value</span><span class="tok-o">()</span>

      <span class="tok-k">if</span> <span class="tok-o">(</span><span class="tok-n">savedOrder</span> <span class="tok-o">!=</span> <span class="tok-kc">null</span> <span class="tok-o">&amp;&amp;</span>
        <span class="tok-o">(</span><span class="tok-n">savedOrder</span><span class="tok-o">.</span><span class="tok-n">eventType</span> <span class="tok-o">==</span> <span class="tok-s">&quot;create&quot;</span><span class="tok-o">))</span> <span class="tok-o">{</span>
        <span class="tok-n">out</span><span class="tok-o">.</span><span class="tok-n">collect</span><span class="tok-o">(</span><span class="tok-n">savedOrder</span><span class="tok-o">)</span>
      <span class="tok-o">}</span>

      <span class="tok-n">orderState</span><span class="tok-o">.</span><span class="tok-n">clear</span><span class="tok-o">()</span>
    <span class="tok-o">}</span>
  <span class="tok-o">}</span>
<span class="tok-o">}</span></code></pre>
</div>
</div>
</div>
</div>
<div class="sect2">
<h3 id="_实现两条流的join">12.9. 实现两条流的Join</h3>
<div class="paragraph">
<p>完整代码如下：</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="pygments highlight"><code data-lang="scala"><span></span><span class="tok-k">import</span> <span class="tok-nn">org.apache.flink.api.common.state.</span><span class="tok-o">{</span><span class="tok-nc">ValueState</span><span class="tok-o">,</span> <span class="tok-nc">ValueStateDescriptor</span><span class="tok-o">}</span>
<span class="tok-k">import</span> <span class="tok-nn">org.apache.flink.streaming.api.TimeCharacteristic</span>
<span class="tok-k">import</span> <span class="tok-nn">org.apache.flink.streaming.api.functions.co.CoProcessFunction</span>
<span class="tok-k">import</span> <span class="tok-nn">org.apache.flink.streaming.api.scala.OutputTag</span>
<span class="tok-k">import</span> <span class="tok-nn">org.apache.flink.streaming.api.scala._</span>
<span class="tok-k">import</span> <span class="tok-nn">org.apache.flink.util.Collector</span>

<span class="tok-k">case</span> <span class="tok-k">class</span> <span class="tok-nc">OrderEvent</span><span class="tok-o">(</span><span class="tok-n">orderId</span><span class="tok-k">:</span> <span class="tok-kt">String</span><span class="tok-o">,</span>
                      <span class="tok-n">eventType</span><span class="tok-k">:</span> <span class="tok-kt">String</span><span class="tok-o">,</span>
                      <span class="tok-n">eventTime</span><span class="tok-k">:</span> <span class="tok-kt">String</span><span class="tok-o">)</span>

<span class="tok-k">case</span> <span class="tok-k">class</span> <span class="tok-nc">PayEvent</span><span class="tok-o">(</span><span class="tok-n">orderId</span><span class="tok-k">:</span> <span class="tok-kt">String</span><span class="tok-o">,</span>
                    <span class="tok-n">eventType</span><span class="tok-k">:</span> <span class="tok-kt">String</span><span class="tok-o">,</span>
                    <span class="tok-n">eventTime</span><span class="tok-k">:</span> <span class="tok-kt">String</span><span class="tok-o">)</span>

<span class="tok-k">object</span> <span class="tok-nc">TwoStreamsJoin</span> <span class="tok-o">{</span>
  <span class="tok-k">val</span> <span class="tok-n">unmatchedOrders</span> <span class="tok-k">=</span> <span class="tok-k">new</span> <span class="tok-nc">OutputTag</span><span class="tok-o">[</span><span class="tok-kt">OrderEvent</span><span class="tok-o">](</span><span class="tok-s">&quot;unmatchedOrders&quot;</span><span class="tok-o">){}</span>
  <span class="tok-k">val</span> <span class="tok-n">unmatchedPays</span> <span class="tok-k">=</span> <span class="tok-k">new</span> <span class="tok-nc">OutputTag</span><span class="tok-o">[</span><span class="tok-kt">PayEvent</span><span class="tok-o">](</span><span class="tok-s">&quot;unmatchedPays&quot;</span><span class="tok-o">){}</span>

  <span class="tok-k">def</span> <span class="tok-n">main</span><span class="tok-o">(</span><span class="tok-n">args</span><span class="tok-k">:</span> <span class="tok-kt">Array</span><span class="tok-o">[</span><span class="tok-kt">String</span><span class="tok-o">])</span><span class="tok-k">:</span> <span class="tok-kt">Unit</span> <span class="tok-o">=</span> <span class="tok-o">{</span>
    <span class="tok-k">val</span> <span class="tok-n">env</span> <span class="tok-k">=</span> <span class="tok-nc">StreamExecutionEnvironment</span><span class="tok-o">.</span><span class="tok-n">getExecutionEnvironment</span>
    <span class="tok-n">env</span><span class="tok-o">.</span><span class="tok-n">setStreamTimeCharacteristic</span><span class="tok-o">(</span><span class="tok-nc">TimeCharacteristic</span><span class="tok-o">.</span><span class="tok-nc">EventTime</span><span class="tok-o">)</span>
    <span class="tok-n">env</span><span class="tok-o">.</span><span class="tok-n">setParallelism</span><span class="tok-o">(</span><span class="tok-mi">1</span><span class="tok-o">)</span>

    <span class="tok-k">val</span> <span class="tok-n">orders</span> <span class="tok-k">=</span> <span class="tok-n">env</span>
      <span class="tok-o">.</span><span class="tok-n">fromCollection</span><span class="tok-o">(</span><span class="tok-nc">List</span><span class="tok-o">(</span>
      <span class="tok-nc">OrderEvent</span><span class="tok-o">(</span><span class="tok-s">&quot;1&quot;</span><span class="tok-o">,</span> <span class="tok-s">&quot;create&quot;</span><span class="tok-o">,</span> <span class="tok-s">&quot;1558430842&quot;</span><span class="tok-o">),</span>
      <span class="tok-nc">OrderEvent</span><span class="tok-o">(</span><span class="tok-s">&quot;2&quot;</span><span class="tok-o">,</span> <span class="tok-s">&quot;create&quot;</span><span class="tok-o">,</span> <span class="tok-s">&quot;1558430843&quot;</span><span class="tok-o">),</span>
      <span class="tok-nc">OrderEvent</span><span class="tok-o">(</span><span class="tok-s">&quot;1&quot;</span><span class="tok-o">,</span> <span class="tok-s">&quot;pay&quot;</span><span class="tok-o">,</span> <span class="tok-s">&quot;1558430844&quot;</span><span class="tok-o">),</span>
      <span class="tok-nc">OrderEvent</span><span class="tok-o">(</span><span class="tok-s">&quot;2&quot;</span><span class="tok-o">,</span> <span class="tok-s">&quot;pay&quot;</span><span class="tok-o">,</span> <span class="tok-s">&quot;1558430845&quot;</span><span class="tok-o">),</span>
      <span class="tok-nc">OrderEvent</span><span class="tok-o">(</span><span class="tok-s">&quot;3&quot;</span><span class="tok-o">,</span> <span class="tok-s">&quot;create&quot;</span><span class="tok-o">,</span> <span class="tok-s">&quot;1558430849&quot;</span><span class="tok-o">),</span>
      <span class="tok-nc">OrderEvent</span><span class="tok-o">(</span><span class="tok-s">&quot;3&quot;</span><span class="tok-o">,</span> <span class="tok-s">&quot;pay&quot;</span><span class="tok-o">,</span> <span class="tok-s">&quot;1558430849&quot;</span><span class="tok-o">)</span>
    <span class="tok-o">)).</span><span class="tok-n">assignAscendingTimestamps</span><span class="tok-o">(</span><span class="tok-k">_</span><span class="tok-o">.</span><span class="tok-n">eventTime</span><span class="tok-o">.</span><span class="tok-n">toLong</span> <span class="tok-o">*</span> <span class="tok-mi">1000</span><span class="tok-o">)</span>
      <span class="tok-o">.</span><span class="tok-n">keyBy</span><span class="tok-o">(</span><span class="tok-s">&quot;orderId&quot;</span><span class="tok-o">)</span>

    <span class="tok-k">val</span> <span class="tok-n">pays</span> <span class="tok-k">=</span> <span class="tok-n">env</span><span class="tok-o">.</span><span class="tok-n">fromCollection</span><span class="tok-o">(</span><span class="tok-nc">List</span><span class="tok-o">(</span>
      <span class="tok-nc">PayEvent</span><span class="tok-o">(</span><span class="tok-s">&quot;1&quot;</span><span class="tok-o">,</span> <span class="tok-s">&quot;weixin&quot;</span><span class="tok-o">,</span> <span class="tok-s">&quot;1558430847&quot;</span><span class="tok-o">),</span>
      <span class="tok-nc">PayEvent</span><span class="tok-o">(</span><span class="tok-s">&quot;2&quot;</span><span class="tok-o">,</span> <span class="tok-s">&quot;zhifubao&quot;</span><span class="tok-o">,</span> <span class="tok-s">&quot;1558430848&quot;</span><span class="tok-o">),</span>
      <span class="tok-nc">PayEvent</span><span class="tok-o">(</span><span class="tok-s">&quot;4&quot;</span><span class="tok-o">,</span> <span class="tok-s">&quot;zhifubao&quot;</span><span class="tok-o">,</span> <span class="tok-s">&quot;1558430850&quot;</span><span class="tok-o">)</span>
    <span class="tok-o">)).</span><span class="tok-n">assignAscendingTimestamps</span><span class="tok-o">(</span><span class="tok-k">_</span><span class="tok-o">.</span><span class="tok-n">eventTime</span><span class="tok-o">.</span><span class="tok-n">toLong</span> <span class="tok-o">*</span> <span class="tok-mi">1000</span><span class="tok-o">)</span>
      <span class="tok-o">.</span><span class="tok-n">keyBy</span><span class="tok-o">(</span><span class="tok-s">&quot;orderId&quot;</span><span class="tok-o">)</span>

    <span class="tok-k">val</span> <span class="tok-n">processed</span> <span class="tok-k">=</span> <span class="tok-n">orders</span>
      <span class="tok-o">.</span><span class="tok-n">connect</span><span class="tok-o">(</span><span class="tok-n">pays</span><span class="tok-o">)</span>
      <span class="tok-o">.</span><span class="tok-n">process</span><span class="tok-o">(</span><span class="tok-k">new</span> <span class="tok-nc">EnrichmentFunction</span><span class="tok-o">)</span>

    <span class="tok-n">processed</span><span class="tok-o">.</span><span class="tok-n">getSideOutput</span><span class="tok-o">[</span><span class="tok-kt">PayEvent</span><span class="tok-o">](</span><span class="tok-n">unmatchedPays</span><span class="tok-o">).</span><span class="tok-n">print</span><span class="tok-o">()</span>
    <span class="tok-n">processed</span><span class="tok-o">.</span><span class="tok-n">getSideOutput</span><span class="tok-o">[</span><span class="tok-kt">OrderEvent</span><span class="tok-o">](</span><span class="tok-n">unmatchedOrders</span><span class="tok-o">).</span><span class="tok-n">print</span><span class="tok-o">()</span>

    <span class="tok-n">env</span><span class="tok-o">.</span><span class="tok-n">execute</span>
  <span class="tok-o">}</span>

  <span class="tok-k">class</span> <span class="tok-nc">EnrichmentFunction</span> <span class="tok-k">extends</span> <span class="tok-nc">CoProcessFunction</span><span class="tok-o">[</span>
    <span class="tok-kt">OrderEvent</span>, <span class="tok-kt">PayEvent</span>, <span class="tok-o">(</span><span class="tok-kt">OrderEvent</span>, <span class="tok-kt">PayEvent</span><span class="tok-o">)]</span> <span class="tok-o">{</span>
    <span class="tok-k">lazy</span> <span class="tok-k">val</span> <span class="tok-n">orderState</span><span class="tok-k">:</span> <span class="tok-kt">ValueState</span><span class="tok-o">[</span><span class="tok-kt">OrderEvent</span><span class="tok-o">]</span> <span class="tok-k">=</span> <span class="tok-n">getRuntimeContext</span>
      <span class="tok-o">.</span><span class="tok-n">getState</span><span class="tok-o">(</span><span class="tok-k">new</span> <span class="tok-nc">ValueStateDescriptor</span><span class="tok-o">[</span><span class="tok-kt">OrderEvent</span><span class="tok-o">](</span><span class="tok-s">&quot;saved order&quot;</span><span class="tok-o">,</span>
        <span class="tok-n">classOf</span><span class="tok-o">[</span><span class="tok-kt">OrderEvent</span><span class="tok-o">]))</span>

    <span class="tok-k">lazy</span> <span class="tok-k">val</span> <span class="tok-n">payState</span><span class="tok-k">:</span> <span class="tok-kt">ValueState</span><span class="tok-o">[</span><span class="tok-kt">PayEvent</span><span class="tok-o">]</span> <span class="tok-k">=</span> <span class="tok-n">getRuntimeContext</span>
      <span class="tok-o">.</span><span class="tok-n">getState</span><span class="tok-o">(</span><span class="tok-k">new</span> <span class="tok-nc">ValueStateDescriptor</span><span class="tok-o">[</span><span class="tok-kt">PayEvent</span><span class="tok-o">](</span><span class="tok-s">&quot;saved pay&quot;</span><span class="tok-o">,</span>
        <span class="tok-n">classOf</span><span class="tok-o">[</span><span class="tok-kt">PayEvent</span><span class="tok-o">]))</span>

    <span class="tok-k">override</span> <span class="tok-k">def</span> <span class="tok-n">processElement1</span><span class="tok-o">(</span><span class="tok-n">order</span><span class="tok-k">:</span> <span class="tok-kt">OrderEvent</span><span class="tok-o">,</span>
                                 <span class="tok-n">context</span><span class="tok-k">:</span> <span class="tok-kt">CoProcessFunction</span><span class="tok-o">[</span>
                                   <span class="tok-kt">OrderEvent</span>,
                                   <span class="tok-kt">PayEvent</span>,
                                   <span class="tok-o">(</span><span class="tok-kt">OrderEvent</span>, <span class="tok-kt">PayEvent</span><span class="tok-o">)]</span><span class="tok-k">#</span><span class="tok-nc">Context</span><span class="tok-o">,</span>
                                 <span class="tok-n">out</span><span class="tok-k">:</span> <span class="tok-kt">Collector</span><span class="tok-o">[(</span><span class="tok-kt">OrderEvent</span>, <span class="tok-kt">PayEvent</span><span class="tok-o">)])</span><span class="tok-k">:</span> <span class="tok-kt">Unit</span> <span class="tok-o">=</span> <span class="tok-o">{</span>
      <span class="tok-k">val</span> <span class="tok-n">pay</span> <span class="tok-k">=</span> <span class="tok-n">payState</span><span class="tok-o">.</span><span class="tok-n">value</span><span class="tok-o">()</span>

      <span class="tok-k">if</span> <span class="tok-o">(</span><span class="tok-n">pay</span> <span class="tok-o">!=</span> <span class="tok-kc">null</span><span class="tok-o">)</span> <span class="tok-o">{</span>
        <span class="tok-n">payState</span><span class="tok-o">.</span><span class="tok-n">clear</span><span class="tok-o">()</span>
        <span class="tok-n">out</span><span class="tok-o">.</span><span class="tok-n">collect</span><span class="tok-o">((</span><span class="tok-n">order</span><span class="tok-o">,</span> <span class="tok-n">pay</span><span class="tok-o">))</span>
      <span class="tok-o">}</span> <span class="tok-k">else</span> <span class="tok-o">{</span>
        <span class="tok-n">orderState</span><span class="tok-o">.</span><span class="tok-n">update</span><span class="tok-o">(</span><span class="tok-n">order</span><span class="tok-o">)</span>
        <span class="tok-c1">// as soon as the watermark arrives,</span>
        <span class="tok-c1">// we can stop waiting for the corresponding pay</span>
        <span class="tok-n">context</span><span class="tok-o">.</span><span class="tok-n">timerService</span>
          <span class="tok-o">.</span><span class="tok-n">registerEventTimeTimer</span><span class="tok-o">(</span><span class="tok-n">order</span><span class="tok-o">.</span><span class="tok-n">eventTime</span><span class="tok-o">.</span><span class="tok-n">toLong</span> <span class="tok-o">*</span> <span class="tok-mi">1000</span><span class="tok-o">)</span>
      <span class="tok-o">}</span>
    <span class="tok-o">}</span>

    <span class="tok-k">override</span> <span class="tok-k">def</span> <span class="tok-n">processElement2</span><span class="tok-o">(</span><span class="tok-n">pay</span><span class="tok-k">:</span> <span class="tok-kt">PayEvent</span><span class="tok-o">,</span>
                                 <span class="tok-n">context</span><span class="tok-k">:</span> <span class="tok-kt">CoProcessFunction</span><span class="tok-o">[</span>
                                   <span class="tok-kt">OrderEvent</span>,
                                   <span class="tok-kt">PayEvent</span>,
                                   <span class="tok-o">(</span><span class="tok-kt">OrderEvent</span>, <span class="tok-kt">PayEvent</span><span class="tok-o">)]</span><span class="tok-k">#</span><span class="tok-nc">Context</span><span class="tok-o">,</span>
                                 <span class="tok-n">out</span><span class="tok-k">:</span> <span class="tok-kt">Collector</span><span class="tok-o">[(</span><span class="tok-kt">OrderEvent</span>, <span class="tok-kt">PayEvent</span><span class="tok-o">)])</span><span class="tok-k">:</span> <span class="tok-kt">Unit</span> <span class="tok-o">=</span> <span class="tok-o">{</span>
      <span class="tok-k">val</span> <span class="tok-n">order</span> <span class="tok-k">=</span> <span class="tok-n">orderState</span><span class="tok-o">.</span><span class="tok-n">value</span><span class="tok-o">()</span>

      <span class="tok-k">if</span> <span class="tok-o">(</span><span class="tok-n">order</span> <span class="tok-o">!=</span> <span class="tok-kc">null</span><span class="tok-o">)</span> <span class="tok-o">{</span>
        <span class="tok-n">orderState</span><span class="tok-o">.</span><span class="tok-n">clear</span><span class="tok-o">()</span>
        <span class="tok-n">out</span><span class="tok-o">.</span><span class="tok-n">collect</span><span class="tok-o">((</span><span class="tok-n">order</span><span class="tok-o">,</span> <span class="tok-n">pay</span><span class="tok-o">))</span>
      <span class="tok-o">}</span> <span class="tok-k">else</span> <span class="tok-o">{</span>
        <span class="tok-n">payState</span><span class="tok-o">.</span><span class="tok-n">update</span><span class="tok-o">(</span><span class="tok-n">pay</span><span class="tok-o">)</span>
        <span class="tok-n">context</span><span class="tok-o">.</span><span class="tok-n">timerService</span><span class="tok-o">.</span><span class="tok-n">registerEventTimeTimer</span><span class="tok-o">(</span><span class="tok-n">pay</span><span class="tok-o">.</span><span class="tok-n">eventTime</span><span class="tok-o">.</span><span class="tok-n">toLong</span> <span class="tok-o">*</span> <span class="tok-mi">1000</span><span class="tok-o">)</span>
      <span class="tok-o">}</span>
    <span class="tok-o">}</span>

    <span class="tok-k">override</span> <span class="tok-k">def</span> <span class="tok-n">onTimer</span><span class="tok-o">(</span><span class="tok-n">timestamp</span><span class="tok-k">:</span> <span class="tok-kt">Long</span><span class="tok-o">,</span>
                         <span class="tok-n">ctx</span><span class="tok-k">:</span> <span class="tok-kt">CoProcessFunction</span><span class="tok-o">[</span><span class="tok-kt">OrderEvent</span>,
                           <span class="tok-kt">PayEvent</span>, <span class="tok-o">(</span><span class="tok-kt">OrderEvent</span>, <span class="tok-kt">PayEvent</span><span class="tok-o">)]</span><span class="tok-k">#</span><span class="tok-nc">OnTimerContext</span><span class="tok-o">,</span>
                         <span class="tok-n">out</span><span class="tok-k">:</span> <span class="tok-kt">Collector</span><span class="tok-o">[(</span><span class="tok-kt">OrderEvent</span>, <span class="tok-kt">PayEvent</span><span class="tok-o">)])</span><span class="tok-k">:</span> <span class="tok-kt">Unit</span> <span class="tok-o">=</span> <span class="tok-o">{</span>
      <span class="tok-k">if</span> <span class="tok-o">(</span><span class="tok-n">payState</span><span class="tok-o">.</span><span class="tok-n">value</span> <span class="tok-o">!=</span> <span class="tok-kc">null</span><span class="tok-o">)</span> <span class="tok-o">{</span>
        <span class="tok-n">ctx</span><span class="tok-o">.</span><span class="tok-n">output</span><span class="tok-o">(</span><span class="tok-n">unmatchedPays</span><span class="tok-o">,</span> <span class="tok-n">payState</span><span class="tok-o">.</span><span class="tok-n">value</span><span class="tok-o">)</span>
        <span class="tok-n">payState</span><span class="tok-o">.</span><span class="tok-n">clear</span><span class="tok-o">()</span>
      <span class="tok-o">}</span>

      <span class="tok-k">if</span> <span class="tok-o">(</span><span class="tok-n">orderState</span><span class="tok-o">.</span><span class="tok-n">value</span> <span class="tok-o">!=</span> <span class="tok-kc">null</span><span class="tok-o">)</span> <span class="tok-o">{</span>
        <span class="tok-n">ctx</span><span class="tok-o">.</span><span class="tok-n">output</span><span class="tok-o">(</span><span class="tok-n">unmatchedOrders</span><span class="tok-o">,</span> <span class="tok-n">orderState</span><span class="tok-o">.</span><span class="tok-n">value</span><span class="tok-o">)</span>
        <span class="tok-n">orderState</span><span class="tok-o">.</span><span class="tok-n">clear</span><span class="tok-o">()</span>
      <span class="tok-o">}</span>
    <span class="tok-o">}</span>
  <span class="tok-o">}</span>
<span class="tok-o">}</span></code></pre>
</div>
</div>
</div>
</div>
</div>
<div class="sect1">
<h2 id="_常见面试题解答">13. 常见面试题解答</h2>
<div class="sectionbody">
<div class="sect2">
<h3 id="_面试题一">13.1. 面试题一</h3>
<div class="paragraph">
<p>问题：公司怎么提交的实时任务，有多少Job Manager？</p>
</div>
<div class="paragraph">
<p>解答：</p>
</div>
<div class="ulist">
<ul>
<li>
<p>我们每次提交都会创建一个新的Flink集群，为每一个每个job提供一个yarn-session，任务之间互相独立，互不影响，方便管理。任务执行完成之后创建的集群也会消失。</p>
</li>
</ul>
</div>
<div class="paragraph">
<p>线上脚本如下：</p>
</div>
<div class="listingblock">
<div class="content">
<pre class="pygments highlight"><code data-lang="shell"><span></span>bin/yarn-session.sh -n <span class="tok-m">7</span> -s <span class="tok-m">8</span> -jm <span class="tok-m">3072</span> -tm <span class="tok-m">32768</span> -qu root.*.*-nm *-* -d</code></pre>
</div>
</div>
<div class="paragraph">
<p>其中申请7个taskManager，每个8核，每个taskmanager有32768M内存。</p>
</div>
<div class="ulist">
<ul>
<li>
<p>集群默认只有一个Job Manager。但为了防止单点故障，我们配置了高可用。我们公司一般配置一个主Job Manager，两个备用Job Manager，然后结合ZooKeeper的使用，来达到高可用。</p>
</li>
</ul>
</div>
</div>
<div class="sect2">
<h3 id="_面试题二">13.2. 面试题二</h3>
<div class="paragraph">
<p>问题：怎么做压力测试和监控？</p>
</div>
<div class="paragraph">
<p>解答：我们一般碰到的压力来自以下几个方面：</p>
</div>
<div class="paragraph">
<p>一，产生数据流的速度如果过快，而下游的算子消费不过来的话，会产生背压问题。背压的监控可以使用Flink Web UI(localhost:8081)来可视化监控，一旦报警就能知道。一般情况下背压问题的产生可能是由于sink这个操作符没有优化好，做一下优化就可以了。比如如果是写入ElasticSearch，那么可以改成批量写入，可以调大ElasticSearch队列的大小等等策略。</p>
</div>
<div class="paragraph">
<p>二，设置水位线的最大延迟时间这个参数，如果设置的过大，可能会造成内存的压力。可以设置的最大延迟时间小一些，然后把迟到元素发送到侧输出流中去。晚一点更新结果。或者使用类似于RocksDB这样的状态后端，RocksDB会开辟堆外存储空间，但IO速度会变慢，需要权衡。</p>
</div>
<div class="paragraph">
<p>三，还有就是滑动窗口的长度如果过长，而滑动距离很短的话，Flink的性能会下降的很厉害。</p>
</div>
<div class="listingblock">
<div class="content">
<pre>参见链接：https://www.infoq.cn/article/sIhs_qY6HCpMQNblTI9M</pre>
</div>
</div>
<div class="paragraph">
<p>四，状态后端使用RocksDB，还没有碰到被撑爆的问题。</p>
</div>
</div>
<div class="sect2">
<h3 id="_面试题三">13.3. 面试题三</h3>
<div class="paragraph">
<p>问题：问什么使用Flink替代Spark？</p>
</div>
<div class="paragraph">
<p>解答：教材里面有Flink和Spark的详细对比。</p>
</div>
</div>
<div class="sect2">
<h3 id="_面试题四">13.4. 面试题四</h3>
<div class="paragraph">
<p>问题：Flink的CheckPoint存在哪里？</p>
</div>
<div class="paragraph">
<p>解答：教材里有。内存，文件系统，或者RocksDB。</p>
</div>
</div>
<div class="sect2">
<h3 id="_面试题五">13.5. 面试题五</h3>
<div class="paragraph">
<p>问题：如果下级存储不支持事务，Flink怎么保证exactly-once？</p>
</div>
<div class="paragraph">
<p>解答：参见教材</p>
</div>
</div>
<div class="sect2">
<h3 id="_面试题六">13.6. 面试题六</h3>
<div class="paragraph">
<p>问题：说一下Flink状态机制？</p>
</div>
<div class="paragraph">
<p>解答：参见教材相关内容。</p>
</div>
</div>
<div class="sect2">
<h3 id="_面试题七">13.7. 面试题七</h3>
<div class="paragraph">
<p>问题：怎么去重？考虑一个实时场景：双十一场景，滑动窗口长度为1小时，滑动距离为10秒钟，亿级用户，计算UV？</p>
</div>
<div class="paragraph">
<p>解答：使用类似于scala的set数据结构或者redis的set数据结构显然是不行的，因为可能有上亿个Key，内存放不下。所以可以考虑使用布隆过滤器（Bloom Filter）来去重。</p>
</div>
</div>
<div class="sect2">
<h3 id="_面试题八">13.8. 面试题八</h3>
<div class="paragraph">
<p>问题：Flink的checkpoint机制对比spark有什么不同和优势？</p>
</div>
<div class="paragraph">
<p>解答：spark streaming的Checkpoint仅仅是针对driver的故障恢复做了数据和元数据的Checkpoint。而flink的checkpoint机制要复杂了很多，它采用的是轻量级的分布式快照，实现了每个操作符的快照，及循环流的在循环的数据的快照。参见教材内容和链接：</p>
</div>
<div class="listingblock">
<div class="content">
<pre>https://cloud.tencent.com/developer/article/1189624</pre>
</div>
</div>
</div>
<div class="sect2">
<h3 id="_面试题九">13.9. 面试题九</h3>
<div class="paragraph">
<p>问题：Flink的Watermark详细说明？</p>
</div>
<div class="paragraph">
<p>解答：见教材。</p>
</div>
</div>
<div class="sect2">
<h3 id="_面试题十">13.10. 面试题十</h3>
<div class="paragraph">
<p>问题：Flink ExactlyOnce语义是如何实现的，状态是如何存储的？</p>
</div>
<div class="paragraph">
<p>解答：见教材。</p>
</div>
</div>
<div class="sect2">
<h3 id="_面试题十一">13.11. 面试题十一</h3>
<div class="paragraph">
<p>问题：Flink CEP编程中当状态没有到达的时候会将数据保存在哪里？</p>
</div>
<div class="paragraph">
<p>解答：CEP当然在流式处理中是要支持EventTime的，那么相对应的要支持数据的晚到现象，也就是watermark的处理逻辑。在Flink的处理逻辑中，将晚到数据明细存储在了Map&lt;Long, List&lt;IN&gt;&gt;的结构中，也就是说，如果watermark设置为当前时间减去5分钟，那么内存中就会存储5分钟的数据，这在我看来，也是对内存的极大损伤之一。</p>
</div>
</div>
<div class="sect2">
<h3 id="_面试题十二">13.12. 面试题十二</h3>
<div class="paragraph">
<p>问题：Flink三种时间概念分别说出应用场景？</p>
</div>
<div class="paragraph">
<p>解答：</p>
</div>
<div class="olist arabic">
<ol class="arabic">
<li>
<p>Event Time：见教材。</p>
</li>
<li>
<p>Processing Time：没有事件时间的情况下，或者对实时性要求超高的情况下。</p>
</li>
<li>
<p>Ingestion Time：存在多个Source Operator的情况下，每个Source Operator会使用自己本地系统时钟指派Ingestion Time。后续基于时间相关的各种操作，都会使用数据记录中的Ingestion Time。</p>
</li>
</ol>
</div>
</div>
<div class="sect2">
<h3 id="_面试题十三">13.13. 面试题十三</h3>
<div class="paragraph">
<p>问题：Flink程序在面对数据高峰期时如何处理？</p>
</div>
<div class="paragraph">
<p>解答：使用大容量的Kafka把数据先放到消息队列里面。再使用Flink进行消费，不过这样会影响到一点实时性。</p>
</div>
</div>
<div class="sect2">
<h3 id="_面试题十四">13.14. 面试题十四</h3>
<div class="paragraph">
<p>问题：flink消费kakfa保证数据不丢失（flink消费kafka数据不丢不重，flink消费kafka的时候挂了怎么恢复数据）</p>
</div>
<div class="paragraph">
<p>解答：端到端一致性（exactly-once），flink会维护消费kafka的偏移量，checkpoint操作。</p>
</div>
</div>
<div class="sect2">
<h3 id="_面试题十五">13.15. 面试题十五</h3>
<div class="paragraph">
<p>问题：Flink过来的数据量太大怎么处理？</p>
</div>
<div class="paragraph">
<p>解答：加机器，考虑使用处理时间（ProcessingTime），前面使用Kafka来做蓄水池，降低消费数据的速度。尽量使用滚动窗口，窗口没有重合，数据不会复制到不同的窗口中去。</p>
</div>
</div>
<div class="sect2">
<h3 id="_面试题十六">13.16. 面试题十六</h3>
<div class="paragraph">
<p>问题：Kafka每5分钟过来的数据量是多少，flink跑的实时频率，flink topN 跑的频率？</p>
</div>
<div class="paragraph">
<p>解答：我们公司一天数据量是100万，所以我们的窗口大小一般设置为1小时，所以数据量大约在10万条左右。</p>
</div>
</div>
<div class="sect2">
<h3 id="_面试题十七">13.17. 面试题十七</h3>
<div class="paragraph">
<p>问题：Flink的资源是如何设置的，设置资源的时候依据是什么？</p>
</div>
<div class="paragraph">
<p>解答：我们公司购买的云计算资源比较多，所以跑平常的任务没有发现什么问题。会提前mock比较大的数据量，做一下压力测试，然后决定使用多少资源。</p>
</div>
<div class="paragraph">
<p>以下6个方面是确定 Flink 集群大小时最先要考虑的一些因素：</p>
</div>
<div class="paragraph">
<p>记录数和每条记录的大小</p>
</div>
<div class="paragraph">
<p>确定集群大小的首要事情就是估算预期进入流计算系统的每秒记录数（也就是我们常说的吞吐量），以及每条记录的大小。不同的记录类型会有不同的大小，这将最终影响 Flink 应用程序平稳运行所需的资源。</p>
</div>
<div class="paragraph">
<p>不同 key 的数量和每个 key 存储的 state 大小</p>
</div>
<div class="paragraph">
<p>应用程序中不同 key 的数量和每个 key 所需要存储的 state 大小，都将影响到 Flink 应用程序所需的资源，从而能高效地运行，避免任何反压。</p>
</div>
<div class="paragraph">
<p>状态的更新频率和状态后端的访问模式</p>
</div>
<div class="paragraph">
<p>第三个考虑因素是状态的更新频率，因为状态的更新通常是一个高消耗的动作。而不同的状态后端（如 RocksDB，Java Heap）的访问模式差异很大，RocksDB 的每次读取和更新都会涉及序列化和反序列化以及 JNI 操作，而 Java Heap 的状态后端不支持增量 checkpoint，导致大状态场景需要每次持久化的数据量较大。这些因素都会显著地影响集群的大小和 Flink 作业所需的资源。</p>
</div>
<div class="paragraph">
<p>网络容量</p>
</div>
<div class="paragraph">
<p>网络容量不仅仅会收到 Flink 应用程序本身的影响，也会受到可能正在交互的 Kafka、HDFS 等外部服务的影响。这些外部服务可能会导致额外的网络流量。例如，启用 replication 可能会在网络的消息 broker 之间产生额外的流量。</p>
</div>
<div class="paragraph">
<p>磁盘带宽</p>
</div>
<div class="paragraph">
<p>如果你的应用程序依赖了基于磁盘的状态后端，如 RocksDB，或者考虑使用 Kafka 或 HDFS，那么磁盘的带宽也需要纳入考虑。</p>
</div>
<div class="paragraph">
<p>机器数量及其可用 CPU 和内存</p>
</div>
<div class="paragraph">
<p>最后但并非最不重要的，在开始应用部署前，你需要考虑集群中可用机器的数量及其可用的 CPU 和内存。这最终确保了在将应用程序投入生产之后，集群有充足的处理能力。</p>
</div>
</div>
</div>
</div>
</div>
<div id="footer">
<div id="footer-text">
Version 1.0<br>
Last updated 2020-04-17 16:05:39 +0800
</div>
</div>
<style>
pre.pygments .hll { background-color: #ffffcc }
pre.pygments  { background: #f8f8f8; }
pre.pygments .tok-c { color: #408080; font-style: italic } /* Comment */
pre.pygments .tok-err { border: 1px solid #FF0000 } /* Error */
pre.pygments .tok-k { color: #008000; font-weight: bold } /* Keyword */
pre.pygments .tok-o { color: #666666 } /* Operator */
pre.pygments .tok-ch { color: #408080; font-style: italic } /* Comment.Hashbang */
pre.pygments .tok-cm { color: #408080; font-style: italic } /* Comment.Multiline */
pre.pygments .tok-cp { color: #BC7A00 } /* Comment.Preproc */
pre.pygments .tok-cpf { color: #408080; font-style: italic } /* Comment.PreprocFile */
pre.pygments .tok-c1 { color: #408080; font-style: italic } /* Comment.Single */
pre.pygments .tok-cs { color: #408080; font-style: italic } /* Comment.Special */
pre.pygments .tok-gd { color: #A00000 } /* Generic.Deleted */
pre.pygments .tok-ge { font-style: italic } /* Generic.Emph */
pre.pygments .tok-gr { color: #FF0000 } /* Generic.Error */
pre.pygments .tok-gh { color: #000080; font-weight: bold } /* Generic.Heading */
pre.pygments .tok-gi { color: #00A000 } /* Generic.Inserted */
pre.pygments .tok-go { color: #888888 } /* Generic.Output */
pre.pygments .tok-gp { color: #000080; font-weight: bold } /* Generic.Prompt */
pre.pygments .tok-gs { font-weight: bold } /* Generic.Strong */
pre.pygments .tok-gu { color: #800080; font-weight: bold } /* Generic.Subheading */
pre.pygments .tok-gt { color: #0044DD } /* Generic.Traceback */
pre.pygments .tok-kc { color: #008000; font-weight: bold } /* Keyword.Constant */
pre.pygments .tok-kd { color: #008000; font-weight: bold } /* Keyword.Declaration */
pre.pygments .tok-kn { color: #008000; font-weight: bold } /* Keyword.Namespace */
pre.pygments .tok-kp { color: #008000 } /* Keyword.Pseudo */
pre.pygments .tok-kr { color: #008000; font-weight: bold } /* Keyword.Reserved */
pre.pygments .tok-kt { color: #B00040 } /* Keyword.Type */
pre.pygments .tok-m { color: #666666 } /* Literal.Number */
pre.pygments .tok-s { color: #BA2121 } /* Literal.String */
pre.pygments .tok-na { color: #7D9029 } /* Name.Attribute */
pre.pygments .tok-nb { color: #008000 } /* Name.Builtin */
pre.pygments .tok-nc { color: #0000FF; font-weight: bold } /* Name.Class */
pre.pygments .tok-no { color: #880000 } /* Name.Constant */
pre.pygments .tok-nd { color: #AA22FF } /* Name.Decorator */
pre.pygments .tok-ni { color: #999999; font-weight: bold } /* Name.Entity */
pre.pygments .tok-ne { color: #D2413A; font-weight: bold } /* Name.Exception */
pre.pygments .tok-nf { color: #0000FF } /* Name.Function */
pre.pygments .tok-nl { color: #A0A000 } /* Name.Label */
pre.pygments .tok-nn { color: #0000FF; font-weight: bold } /* Name.Namespace */
pre.pygments .tok-nt { color: #008000; font-weight: bold } /* Name.Tag */
pre.pygments .tok-nv { color: #19177C } /* Name.Variable */
pre.pygments .tok-ow { color: #AA22FF; font-weight: bold } /* Operator.Word */
pre.pygments .tok-w { color: #bbbbbb } /* Text.Whitespace */
pre.pygments .tok-mb { color: #666666 } /* Literal.Number.Bin */
pre.pygments .tok-mf { color: #666666 } /* Literal.Number.Float */
pre.pygments .tok-mh { color: #666666 } /* Literal.Number.Hex */
pre.pygments .tok-mi { color: #666666 } /* Literal.Number.Integer */
pre.pygments .tok-mo { color: #666666 } /* Literal.Number.Oct */
pre.pygments .tok-sa { color: #BA2121 } /* Literal.String.Affix */
pre.pygments .tok-sb { color: #BA2121 } /* Literal.String.Backtick */
pre.pygments .tok-sc { color: #BA2121 } /* Literal.String.Char */
pre.pygments .tok-dl { color: #BA2121 } /* Literal.String.Delimiter */
pre.pygments .tok-sd { color: #BA2121; font-style: italic } /* Literal.String.Doc */
pre.pygments .tok-s2 { color: #BA2121 } /* Literal.String.Double */
pre.pygments .tok-se { color: #BB6622; font-weight: bold } /* Literal.String.Escape */
pre.pygments .tok-sh { color: #BA2121 } /* Literal.String.Heredoc */
pre.pygments .tok-si { color: #BB6688; font-weight: bold } /* Literal.String.Interpol */
pre.pygments .tok-sx { color: #008000 } /* Literal.String.Other */
pre.pygments .tok-sr { color: #BB6688 } /* Literal.String.Regex */
pre.pygments .tok-s1 { color: #BA2121 } /* Literal.String.Single */
pre.pygments .tok-ss { color: #19177C } /* Literal.String.Symbol */
pre.pygments .tok-bp { color: #008000 } /* Name.Builtin.Pseudo */
pre.pygments .tok-fm { color: #0000FF } /* Name.Function.Magic */
pre.pygments .tok-vc { color: #19177C } /* Name.Variable.Class */
pre.pygments .tok-vg { color: #19177C } /* Name.Variable.Global */
pre.pygments .tok-vi { color: #19177C } /* Name.Variable.Instance */
pre.pygments .tok-vm { color: #19177C } /* Name.Variable.Magic */
pre.pygments .tok-il { color: #666666 } /* Literal.Number.Integer.Long */
</style>
</body>
</html>